문제 >> 1012 : 유기농배추
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 63 64 65 66 67 | import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Main_1012 { //유기농 배추 static int[][] map; static int[] dy = {0,0,-1,1}; static int[] dx = {-1,1,0,0}; static int M,N; public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(bf.readLine()); for(int tc=1;tc<=T;tc++) { StringTokenizer st = new StringTokenizer(bf.readLine()," "); M = Integer.parseInt(st.nextToken()); //가로 N = Integer.parseInt(st.nextToken()); //세로 int K = Integer.parseInt(st.nextToken()); //배추개수 map = new int[N][M]; for(int i=0;i<K;i++) { st = new StringTokenizer(bf.readLine()," "); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); map[y][x]=1; } int ans=0; for(int i=0;i<N;i++) { for(int j=0;j<M;j++) { if(map[i][j] == 1) { dfs(i,j); ans++; } } } System.out.println(ans); }//end of tc } static void dfs(int y, int x) { map[y][x]=0; //visited check for(int i=0;i<4;i++) { int ny = y+dy[i]; int nx = x+dx[i]; if(ny<0 || ny>N-1 || nx<0 || nx>M-1) continue; if(map[ny][nx] == 1) dfs(ny,nx); } return ; } } | cs |
'Algorithm Problem Solving' 카테고리의 다른 글
[SWEA] 1861 : 정사각형 방 (0) | 2019.03.07 |
---|---|
[BOJ] 8983 : 사냥꾼 / [JUNGOL] 2364 : 사냥꾼 (1) | 2019.03.07 |
[BOJ] 1931 : 회의실배정 (++그리디 알고리즘에 대한 고찰) (2) | 2019.02.17 |
[SWEA] 2819 격자판의 숫자 이어 붙이기 (0) | 2019.02.16 |
[BOJ] 9999 : 구구 **결정적 힌트** (5) | 2019.02.13 |