https://www.acmicpc.net/problem/4963
정사각형으로 이루어져 있는 섬과 바다 지도가 주어진다. 섬의 개수를 세는 프로그램을 작성하시오.

한 정사각형과 가로, 세로 또는 대각선으로 연결되어 있는 사각형은 걸어갈 수 있는 사각형이다.
두 정사각형이 같은 섬에 있으려면, 한 정사각형에서 다른 정사각형으로 걸어서 갈 수 있는 경로가 있어야 한다. 지도는 바다로 둘러싸여 있으며, 지도 밖으로 나갈 수 없다.
입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다.
둘째 줄부터 h개 줄에는 지도가 주어진다. 1은 땅, 0은 바다이다.
입력의 마지막 줄에는 0이 두 개 주어진다.
각 테스트 케이스에 대해서, 섬의 개수를 출력한다.
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
0
1
1
3
1
9
package graph_search;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main_4963 {
private static int width;
private static int height;
private static int[][] map;
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static StringTokenizer st;
private static boolean play;
private static boolean[][] visited;
private static int result;
// 좌우, 위아래, 대각선
private static int[][] direction = {
{1, 0}, {-1, 0},
{0, 1}, {0, -1},
{1, 1}, {1, -1}, {-1, 1}, {-1, -1}
};
public static void main(String[] args) throws IOException {
inputWidthAndHeight();
while (play) {
input();
process();
output();
inputWidthAndHeight();
}
}
private static void checkPlay() {
play = !(width == 0 && height == 0);
}
private static void inputWidthAndHeight() throws IOException {
st = new StringTokenizer(br.readLine());
width = Integer.parseInt(st.nextToken());
height = Integer.parseInt(st.nextToken());
checkPlay();
}
private static void input() throws IOException {
map = new int[width][height];
visited = new boolean[width][height];
for (int y = 0; y < height; y++) {
st = new StringTokenizer(br.readLine());
for (int x = 0; x < width; x++) {
map[x][y] = Integer.parseInt(st.nextToken());
}
}
}
private static void process() {
result = 0;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (visited[x][y] || map[x][y] == 0) {
continue;
}
dfs(x,y);
result++;
}
}
}
private static void dfs(int startX, int startY) {
int newX;
int newY;
visited[startX][startY] = true;
for (int i = 0; i < 8; i++) {
newX = startX + direction[i][0];
newY = startY + direction[i][1];
if (newX < 0 || newY < 0 || newX >= width || newY >= height) {
continue;
}
if (map[newX][newY] == 0) {
continue;
}
if (visited[newX][newY]) {
continue;
}
dfs(newX, newY);
}
}
private static void output() {
System.out.println(result);
}
}