https://www.acmicpc.net/problem/4963
4963번: 섬의 개수
입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도
www.acmicpc.net
문제

코드
import java.io.*;
import java.util.*;
public class Main {
static int[][] g;
static int w;
static int h;
static int dx[] = {-1, 1, 0, 0, 1, 1, -1, -1};
static int dy[] = {0, 0, -1, 1, -1, 1, 1, -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));
StringBuilder sb = new StringBuilder();
while(true) {
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
w = Integer.parseInt(st.nextToken());
h = Integer.parseInt(st.nextToken());
if(w==0 && h==0) break;
g = new int[h][w];
for (int i = 0; i < h; i++) {
st = new StringTokenizer(br.readLine(), " ");
for (int j = 0; j < w; j++) {
g[i][j] = Integer.parseInt(st.nextToken());
}
}
int count=0;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if(g[i][j]==1) {
count++;
dfs(i,j);
}
}
}
sb.append(count+"\n");
}
bw.write(sb+"");
bw.flush();
}
public static void dfs(int i, int j) {
g[i][j] = 0;
for(int k=0;k<8;k++) {
int x = i + dx[k];
int y = j + dy[k];
if(x<0 || y<0 || x>=h || y>=w) continue;
if(g[x][y] == 1) {
dfs(x,y);
}
}
}
}
해결방법
그래프를 입력받아 모든 칸을 탐색하여 땅(1)이면 결과값(섬의 개수)을 1 증가시키고 dfs를 실행해 이어져있는 땅을 모두 물(0)로 만들었다. 이렇게 할 경우 섬이 총 몇 개인지 구할 수 있다.
'알고리즘 > 백준' 카테고리의 다른 글
2468번 : 안전 영역 (0) | 2022.08.27 |
---|---|
7562번 : 나이트의 이동 (0) | 2022.08.25 |
7576번 : 토마토 (0) | 2022.08.23 |
11724번 : 연결 요소의 개수 (0) | 2022.08.21 |
2776번 : 암기왕 (0) | 2022.08.21 |