Sangwon Coding

섬의 개수 본문

알고리즘/DFS, BFS

섬의 개수

SW1 2019. 11. 11. 17:03

문제

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

 

 

한 정사각형과 가로, 세로 또는 대각선으로 연결되어 있는 사각형은 걸어갈 수 있는 사각형이다. 

두 정사각형이 같은 섬에 있으려면, 한 정사각형에서 다른 정사각형으로 걸어서 갈 수 있는 경로가 있어야 한다. 지도는 바다로 둘러쌓여 있으며, 지도 밖으로 나갈 수 없다.

입력

입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다.

둘째 줄부터 h개 줄에는 지도가 주어진다. 1은 땅, 0은 바다이다.

입력의 마지막 줄에는 0이 두 개 주어진다.

출력

각 테스트 케이스에 대해서, 섬의 개수를 출력한다.

 

 

앞서 포스팅했던 유기농 배추와 비슷한 유형의 문제였기에 쉽게 풀 수 있었습니다!

 

import java.util.*;

class Main {
	static int w;	// 너비
	static int h;	// 높이
	static int[][] arr;	// 섬위치 배열
	static int[] dx = { 0, 1, 0, -1, 1, 1, -1, -1 };	// 8방향 x좌표
	static int[] dy = { 1, 0, -1, 0, 1, -1, 1, -1 };	// 8방향 y좌표
	static int cnt = 0;

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);

		while (true) {
			w = scan.nextInt();
			h = scan.nextInt();

			if (w == 0 && h == 0)
				break;

			arr = new int[h][w];

			for (int i = 0; i < h; i++) {
				for (int j = 0; j < w; j++) {
					arr[i][j] = scan.nextInt();
				}
			}

			while (find(arr) != null) {
				bfs(find(arr).x, find(arr).y);
			}
			System.out.println(cnt);
			cnt = 0;
		}

	}

	static void bfs(int x, int y) {	// bfs
		Queue<Dot> q = new LinkedList<Dot>();
		q.add(new Dot(x, y));
		arr[x][y] = 0;
		
		while (!q.isEmpty()) {
			Dot next = q.poll();

			for (int i = 0; i < 8; i++) {
				int next_x = next.x + dx[i];
				int next_y = next.y + dy[i];

				if (next_x < 0 || next_y < 0 || next_x >= h || next_y >= w || arr[next_x][next_y] == 0)
					continue;

				arr[next_x][next_y] = 0;
				q.add(new Dot(next_x, next_y));
			}
		}
		cnt++;
	}

	static Dot find(int[][] arr) {	// 섬 위치 찾기 함수
		Dot d = null;
		for (int i = 0; i < h; i++) {
			for (int j = 0; j < w; j++) {
				if (arr[i][j] == 1) {
					d = new Dot(i, j);
					break;
				}
			}
			if (d != null)
				break;
		}
		return d;
	}

}

class Dot {
	int x;
	int y;

	Dot(int x, int y) {
		this.x = x;
		this.y = y;
	}
}

 

문제출처

https://www.acmicpc.net/problem/4963

'알고리즘 > DFS, BFS' 카테고리의 다른 글

괄호 추가하기  (0) 2019.11.14
토마토  (0) 2019.11.14
유기농 배추  (0) 2019.11.11
미로 탐색  (0) 2019.11.07
연결 요소의 개수  (0) 2019.11.07
Comments