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);
}
}
}