○ 기술면접/알고리즘
DFS: 섬의 개수 (백준 4963)
ZEROMI
2023. 3. 22. 21:22
728x90
○ 문제
정사각형으로 이루어져 있는 섬과 바다 지도가 주어진다. 섬의 개수를 세는 프로그램을 작성하시오.
한 정사각형과 가로, 세로 또는 대각선으로 연결되어 있는 사각형은 걸어갈 수 있는 사각형이다.
두 정사각형이 같은 섬에 있으려면, 한 정사각형에서 다른 정사각형으로 걸어서 갈 수 있는 경로가 있어야 한다. 지도는 바다로 둘러싸여 있으며, 지도 밖으로 나갈 수 없다.
○ 입력
입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 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
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.util.StringTokenizer;
public class Main {
static int width;
static int height;
static int[][] map;
static boolean[][] check;//방문처리
static int count;
static int[] xArr = {-1,-1,-1,0,0,1,1,1};//상하좌우대각선
static int[] yArr = {-1,0,1,-1,1,-1,0,1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String wh = null;
while ((wh = br.readLine()) != null && !wh.equals("0 0")) {
StringTokenizer st = new StringTokenizer(wh);
width = Integer.parseInt(st.nextToken());
height = Integer.parseInt(st.nextToken());
map = new int[height][width];
check = new boolean[height][width];
count = 0;
//map 배열 생성
for (int h = 0; h < height; h++) {
String str = br.readLine();
st = new StringTokenizer(str);
for (int w = 0; w < width; w++) {
map[h][w] = Integer.parseInt(st.nextToken());
}
}
//탐색
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
if (map[h][w] == 1 && !check[h][w]) {
count++;
findIsland(h, w);
}
}
}
bw.write(String.valueOf(count)+"\n");
}
bw.flush();
bw.close();
}
//상하좌우대각선 좌표 찍어 탐색
public static void findIsland(int x, int y) {
check[x][y] = true;
int xx = -1;
int yy = -1;
for (int i = 0; i < xArr.length; i++) {
if ((xx = x+xArr[i]) > -1 && xx < height
&& (yy = y+yArr[i]) > -1 && yy < width
&& map[xx][yy] == 1 && !check[xx][yy]) {
findIsland(xx, yy);
}
}
}
}
○ 확인
Length check 할 때 기준점 좀 잘 확인하자.. width 재려면 length가 아니잖아ㅠ
상하좌우대각선 지문 주의, 유형을 외우면 생각보다 쉽네
728x90