알고리즘/백준 등

[백준] 섬의개수

컵라면만두세트 2021. 2. 17. 22:24

dfs를 이용한 문제 

package silver2;
import java.util.Scanner;

public class 섬의개수내이해 {
	//
	static int[] dr = {-1, -1, 0, 1, 1, 1, 0, -1};
	static int[] dc = {0, 1, 1, 1, 0, -1, -1, -1};
	static int W, H;
	static int[][] map;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(true) {
			W = sc.nextInt();
			H = sc.nextInt();
			if( W == 0 && H == 0 )
				break;
			map = new int[H][W];
			for(int i = 0; i < H; i++) {
				for(int j = 0; j < W; j++)
					map[i][j] = sc.nextInt();
			}
			int cnt = 0;
			for(int i = 0; i < H; i++) {
				for(int j = 0; j < W; j++) {
					//1을 만나면, 해당위치를 0으로 바꾸고, 재귀적으로 8방을 다 검사
					if(map[i][j] == 1) {
						cnt++;
						dfs(i, j);
					}
				}
			}
			System.out.println(cnt);
		}
	}
	static void dfs(int r, int c) {
		map[r][c] = 0;
		for(int d = 0; d < 8; d++) {
			int nr = r + dr[d];
			int nc = c + dc[d];
			// 나가는 검사 맵검사 
			if( nr < 0 || nc < 0 || nr >= H || nc >= W)
				continue;
			if(map[nr][nc] == 0 )
				continue;
			dfs(nr, nc);
		}
	}
}

'알고리즘 > 백준 등' 카테고리의 다른 글

[백준] 방배정  (0) 2021.02.22
DFS 예제  (0) 2021.02.18
[백준] 보물  (0) 2021.02.13
[백준] 색종이  (0) 2021.02.09
[백준] 요세푸스 문제  (0) 2021.02.08