Completion over Perfection

백준 1012 - 유기농배추 DFS (JAVA) 본문

앨고리듬 알고리즘

백준 1012 - 유기농배추 DFS (JAVA)

난차차 2020. 11. 6. 22:18
반응형

백준 1012 - 유기농배추 DFS (JAVA)

 

 

DFS의 정석과도 같은 문제네요.

 

www.acmicpc.net/problem/1000

 

1000번: A+B

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

www.acmicpc.net

visits처리를 잘못해서 좀 헤매다가 풀었습니다.

DFS visits 처리는 DFS들어가면서 바로 해주는게 좋은것 같네요. 

 

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
import java.util.*;
 
public class Yuginong {
    
    static int t,n,m,k,result;
    static int map [][];
    static boolean visits[][];
    static int dx[] = {1-100};
    static int dy[] = {001-1};
 
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        
        t = sc.nextInt();
        
        for (int test_case=1; test_case<=t; test_case++) {
            
            m = sc.nextInt();
            n = sc.nextInt();
            k = sc.nextInt();
            
            map = new int[n+2][m+2];
            visits = new boolean[n+2][m+2];
            result = 0;
            
            for(int i=1; i<=k; i++) {
                int temp1 = sc.nextInt()+1;
                int temp2 = sc.nextInt()+1;                
                map[temp2][temp1] = 1;
            }
            
            
            for(int i=1; i<=n; i++) {
                for(int j=1; j<=m; j++) {
                    if(visits[i][j]==false && map[i][j] ==1) {
                        visits[i][j] =true;
                        dfs(i, j);
                        result++;
                    }
                }
            }
            System.out.println(result);
        }
    }
    
    private static void dfs(int x, int y) {
        visits[x][y] = true// 방문체크
        for(int i=0; i<4; i++) {
            int new_x = x + dx[i]; // 1 -1 0 0
            int new_y = y + dy[i]; // 0 0 1 -1
            
            if (new_x<=|| new_y<=|| new_x>=0 || new_y>=0) {
                if(visits[new_x][new_y]==false && map[new_x][new_y]==1) {
                    dfs(new_x,new_y);
                }
            }    
        }
    }
}
 
 
cs

 

 

반응형
Comments