Sangwon Coding

다리 만들기 본문

알고리즘/DFS, BFS

다리 만들기

SW1 2019. 11. 17. 19:04

문제

여러 섬으로 이루어진 나라가 있다. 이 나라의 대통령은 섬을 잇는 다리를 만들겠다는 공약으로 인기몰이를 해 당선될 수 있었다. 하지만 막상 대통령에 취임하자, 다리를 놓는다는 것이 아깝다는 생각을 하게 되었다. 그래서 그는, 생색내는 식으로 한 섬과 다른 섬을 잇는 다리 하나만을 만들기로 하였고, 그 또한 다리를 가장 짧게 하여 돈을 아끼려 하였다.

이 나라는 N×N크기의 이차원 평면상에 존재한다. 이 나라는 여러 섬으로 이루어져 있으며, 섬이란 동서남북으로 육지가 붙어있는 덩어리를 말한다. 다음은 세 개의 섬으로 이루어진 나라의 지도이다.

 

 

위의 그림에서 색이 있는 부분이 육지이고, 색이 없는 부분이 바다이다. 이 바다에 가장 짧은 다리를 놓아 두 대륙을 연결하고자 한다. 가장 짧은 다리란, 다리가 격자에서 차지하는 칸의 수가 가장 작은 다리를 말한다. 다음 그림에서 두 대륙을 연결하는 다리를 볼 수 있다.

 

 

물론 위의 방법 외에도 다리를 놓는 방법이 여러 가지 있으나, 위의 경우가 놓는 다리의 길이가 3으로 가장 짧다(물론 길이가 3인 다른 다리를 놓을 수 있는 방법도 몇 가지 있다).

지도가 주어질 때, 가장 짧은 다리 하나를 놓아 두 대륙을 연결하는 방법을 찾으시오.

입력

첫 줄에는 지도의 크기 N(100이하의 자연수)가 주어진다. 그 다음 N줄에는 N개의 숫자가 빈칸을 사이에 두고 주어지며, 0은 바다, 1은 육지를 나타낸다. 항상 두 개 이상의 섬이 있는 데이터만 입력으로 주어진다.

출력

첫째 줄에 가장 짧은 다리의 길이를 출력한다.

 

 

import java.util.*;

class Main {
	static int n;
	static int[][] board;
	static boolean[][] is_island;	// 섬인지 여부
	static int[] dx = { 1, 0, -1, 0 };
	static int[] dy = { 0, 1, 0, -1 };
	static int island_num = 1;	// 섬마다의 번호
	static int min = Integer.MAX_VALUE;	// 최소 다리 개수
	static Queue<Dot> queue = new LinkedList<Dot>();	// 섬 좌표를 담을 큐

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

		board = new int[n][n];
		is_island = new boolean[n][n];

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				board[i][j] = scan.nextInt();
				is_island[i][j] = false;
			}
		}

		while (find() != null) {
			bfs(find().x, find().y);
		}

		for (int i = 1; i < island_num; i++) {
			for (int j = 0; j < n; j++) {
				for (int k = 0; k < n; k++) {
					if (board[j][k] == i && is_island[j][k] == true)	// 섬 번호별로 큐에 삽입
						queue.add(new Dot(j, k));
				}
			}
			while (!queue.isEmpty()) {	// 해당 섬의 큐가 빌 때까지 탐색
				bfs2(board, i);
			}
		}

		System.out.println(min);
	}

	static Dot find() {
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (board[i][j] == 1 && is_island[i][j] == false) {
					return new Dot(i, j);
				}
			}
		}
		return null;
	}

	static void bfs(int x, int y) {	// 섬마다 번호를 매기기 위한 bfs
		Queue<Dot> q = new LinkedList<Dot>();
		q.add(new Dot(x, y));
		board[q.peek().x][q.peek().y] = island_num;
		is_island[q.peek().x][q.peek().y] = true;

		while (!q.isEmpty()) {
			Dot d = q.poll();

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

				if (next_x < 0 || next_y < 0 || next_x >= n || next_y >= n || board[next_x][next_y] == 0
						|| is_island[next_x][next_y] == true)
					continue;

				q.add(new Dot(next_x, next_y));
				board[next_x][next_y] = island_num;
				is_island[next_x][next_y] = true;
			}
		}
		island_num++;
	}

	static void bfs2(int[][] b, int num) {	// 다리수를 탐색하기 위한 bfs
		int[][] temp = new int[n][n];
		boolean[][] check_temp = new boolean[n][n];
		temp = b;

		Queue<Dot> q = new LinkedList<Dot>();
		q.add(queue.poll());
		check_temp[q.peek().x][q.peek().x] = true;

		while (!q.isEmpty()) {
			Dot d = q.poll();
			for (int i = 0; i < 4; i++) {
				int next_x = d.x + dx[i];
				int next_y = d.y + dy[i];

				if (next_x < 0 || next_y < 0 || next_x >= n || next_y >= n || check_temp[next_x][next_y] == true)
					continue;

				if (is_island[next_x][next_y] == true) {
					if (temp[next_x][next_y] != num) {
						if((temp[d.x][d.y] - num) < min) {
							min = temp[d.x][d.y] - num;
						}
					}
					continue;
				}

				q.add(new Dot(next_x, next_y));
				temp[next_x][next_y] = temp[d.x][d.y] + 1;
				check_temp[next_x][next_y] = true;
			}
		}
	}
}

class Dot {
	int x;
	int y;

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

 

문제출처

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

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

안전 영역  (0) 2019.11.19
벽 부수고 이동하기  (0) 2019.11.18
영역 구하기  (0) 2019.11.16
단지번호 붙이기  (0) 2019.11.15
적록색약  (0) 2019.11.15
Comments