문제 출처
https://www.acmicpc.net/problem/4963
4963번: 섬의 개수
문제 정사각형으로 이루어져 있는 섬과 바다 지도가 주어진다. 섬의 개수를 세는 프로그램을 작성하시오. 한 정사각형과 가로, 세로 또는 대각선으로 연결되어 있는 사각형은 걸어갈 수 있는 사각형이다. 두 정사각형이 같은 섬에 있으려면, 한 정사각형에서 다른 정사각형으로 걸어서 갈 수 있는 경로가 있어야 한다. 지도는 바다로 둘러쌓여 있으며, 지도 밖으로 나갈 수 없다. 입력 입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는
www.acmicpc.net
접근 방식 및 풀이
- BFS, DFS 모두 사용하여 해결할 수 있다.
- 아래 블로그 내용을 참고하여 구현하였다. (개인적으로 제일 깔끔하게 구현하신거 같다.)
https://developer-mac.tistory.com/66
[Java]백준 4963번 :: 섬의 개수
백준 4963번 :: 섬의 개수 백준 온라인 저지 4963번 - 섬의 개수 Java 알고리즘 문제풀이 코딩테스트 DFS, BFS : https://developer-mac.tistory.com/64 풀이 그래프를 이용한 경로탐색 알고리즘에 대표적으로 2가..
developer-mac.tistory.com
- 손코딩..
소스 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
class Pairs{
int x ;
int y ;
public Pairs(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Main {
static int[] dx = {0, 0, 1, -1, 1, -1, 1, -1};
static int[] dy = {-1, 1, 0, 0, -1 , 1, 1, -1};
static int[][] arr;
static int[][] maps;
/* DFS */
private static void dfs(int x , int y , int count, int w, int h ){
maps[x][y] = count;
for (int i = 0; i < dx.length; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if(0<=nx && nx < h && 0<=ny && ny < w){
if(arr[nx][ny] ==1 && maps[nx][ny] == 0){
dfs(nx, ny, count, w, h);
}
}
}
}
private static void bfs(int x , int y , int count, int w, int h){
Queue<Pairs> queue = new LinkedList<Pairs>();
queue.add(new Pairs(x,y));
maps[x][y] = count;
while(!queue.isEmpty()){
Pairs p = queue.remove();
x = p.x;
y = p.y;
for (int i = 0; i < dx.length; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if(0<=nx && nx < h && 0<=ny && ny < w){
if(arr[nx][ny] ==1 && maps[nx][ny] == 0){
bfs(nx, ny, count, w, h);
}
}
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true){
String[] tmp = br.readLine().split(" ");
int w = Integer.parseInt(tmp[0]);
int h = Integer.parseInt(tmp[1]);
if(w==0 && h ==0)
break;
arr = new int[h][w];
for (int i = 0; i <h ; i++) {
String[] tmpmap = br.readLine().split(" ");
// StringTokenizer st = new StringTokenizer(br.readLine());
for (int j = 0; j < w; j++) {
// arr[i][j] = Integer.parseInt(st.nextToken());
arr[i][j] = Integer.parseInt(tmpmap[j]);
}
}
int count = 0;
maps = new int[h][w];
for (int i = 0; i < h; i++) {
for (int j = 0; j <w ; j++) {
if(arr[i][j] == 1 && maps[i][j] == 0){
bfs(i,j,++count, w,h);
}
}
}
System.out.println(count);
}
}
}
결과
'Competition > Baekjoon' 카테고리의 다른 글
[백준] 2261번 자바 (0) | 2020.03.23 |
---|---|
[백준] 2667번 단지번호 매기기 (0) | 2020.03.22 |
[백준] 11655번 ROT13 (0) | 2020.03.21 |