Algorithm
[백준-4963번/Java] 섬의 개수
1984
2022. 11. 11. 19:43
* 재귀 함수를 사용하여 풀었다.
import java.util.*;
import java.io.*;
public class Main {
static int[][] map;
static int w;
static int h;
private static int landChecker(int i, int j) {// i - w , j - h
int count = 0;
try {
if (i < w && j < h && map[i][j] == 1) {
count = 1;
map[i][j] = 0;
landChecker(i - 1, j - 1);
landChecker(i , j - 1);
landChecker(i + 1, j - 1);
landChecker(i - 1, j);
landChecker(i + 1, j);
landChecker(i - 1, j + 1);
landChecker(i, j + 1);
landChecker(i + 1, j + 1);
}
} catch (ArrayIndexOutOfBoundsException e) {
// TODO: handle exception
}
return count;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
w = sc.nextInt();
h = sc.nextInt();
if (w == 0 && h == 0)
break;
map = new int[w][h];
// 지도 저장
for (int j = 0; j < h; j++) {
for (int i = 0; i < w; i++) {
map[i][j] = sc.nextInt();
}
}
int island_cnt = 0;
// 섬 확인 (landChecker)
for (int j = 0; j < h; j++) {
for (int i = 0; i < w; i++) {
island_cnt += landChecker(i, j);
}
}
System.out.println(island_cnt);
}
sc.close();
}
}
728x90