1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.Scanner;
import java.io.FileInputStream;
 
class Solution {
    static int[][] field;
    static int[][] visited;
    static int m;
    static int n;
 
    public static void main(String args[]) throws Exception {
        // Scanner sc = new Scanner(new FileInputStream("sample_input.txt"));
 
        Scanner sc = new Scanner(System.in);
 
        int T = sc.nextInt();
 
        for (int test_case = 0; test_case < T; test_case++) {
            m = sc.nextInt(); // 가로
            n = sc.nextInt(); // 세로
            int k = sc.nextInt();
            int cnt = 0;
 
            field = new int[n][m];
            visited = new int[n][m];
 
            for (int i = 0; i < k; i++) {
                int x = sc.nextInt(); // 가로
                int y = sc.nextInt(); // 세로
                field[y][x] = 1;
            }
 
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (field[i][j] == 1 && visited[i][j] == 0) {
                        DFS(i, j);
                        cnt++;
                    }
                }
            }
 
            System.out.println(cnt);
 
        } // test_case for
 
    } // main
 
    static void DFS(int cur_y, int cur_x) {
        int move_x[] = { 001-1 };
        int move_y[] = { 1-100 };
 
        visited[cur_y][cur_x] = 1;
 
        for (int i = 0; i < 4; i++) {
            int next_x = cur_x + move_x[i];
            int next_y = cur_y + move_y[i];
 
            if (next_x >= 0 && next_x < m && next_y >= 0 && next_y < n) {
                if (field[next_y][next_x] == 1 && visited[next_y][next_x] == 0)
                    DFS(next_y, next_x);
            }
        }
 
    } // DFS
 
}
cs

'공부 > 알고리즘문제' 카테고리의 다른 글

백준 2644 촌수계산  (0) 2017.04.15
백준 1260 DFS와 BFS  (0) 2017.04.15
백준 13458 시험 감독  (0) 2017.04.12
백준 14499 주사위 굴리기  (0) 2017.04.12
코드그라운드 시험 공부  (0) 2017.04.11