Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Tags
more
Archives
Today
Total
관리 메뉴

코드와이

[BAEKJOON] 2146. 다리 만들기 본문

acmicpc

[BAEKJOON] 2146. 다리 만들기

코드와이 2021. 6. 16. 18:10

 

문제링크

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

 

2146번: 다리 만들기

여러 섬으로 이루어진 나라가 있다. 이 나라의 대통령은 섬을 잇는 다리를 만들겠다는 공약으로 인기몰이를 해 당선될 수 있었다. 하지만 막상 대통령에 취임하자, 다리를 놓는다는 것이 아깝다

www.acmicpc.net

 

package acmicpc.Gold3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class 다리_만들기 {

	static int n, map[][], ans, area[][];
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		
		n = Integer.parseInt(br.readLine());
		map = new int[n][n];
		area = new int[n][n];
		for(int i = 0 ; i < n ; i++) {
			st = new StringTokenizer(br.readLine());
			for(int j = 0 ; j < n ; j++) {
				map[i][j] = Integer.parseInt(st.nextToken());
			}
		}
		
		int x = 1;
		for(int i = 0 ; i < n ; i++) {
			for(int j = 0 ; j < n ; j++) {
				if(map[i][j] == 1 && area[i][j] == 0) {
					go(i,j,x);
					x++;
				}
			}
		}
		
		ans = Integer.MAX_VALUE;
		for(int i = 0 ; i < n ; i++) {
			for(int j = 0 ; j < n ; j++) {
				if(map[i][j] != 0) {
					build(i,j,area[i][j]);
				}
			}
		}
		
		System.out.println(ans - 1);
		
	}
	
	static int[] dr = {-1,1,0,0};
	static int[] dc = {0,0,-1,1};
	// 인접한 지역별로 id 부여해주기
	public static void go(int r, int c, int id) {
		area[r][c] = id;
		
		for(int d = 0 ; d < 4 ; d++) {
			int nr = r + dr[d];
			int nc = c + dc[d];
			if(nr < 0 || nc < 0 || nr >= n || nc >= n) continue;
			if(map[nr][nc] == 1 && area[nr][nc] == 0) {
				go(nr, nc, id);
			}
		}
	}
	
	// 다른 id가 있으면 다리 만들기
	// ans 값과 비교해서 ans 최신화
	public static void build(int r, int c, int id) {
		for(int i = 0 ; i < n ; i++) {
			for(int j = 0 ; j < n ; j++) {
				if(map[i][j] != 0 && area[i][j] != id && ans > Math.abs(i - r) + Math.abs(j - c)) {
					ans = Math.abs(i - r) + Math.abs(j - c);
				}
			}
		}
	}
}

'acmicpc' 카테고리의 다른 글

[BAEKJOON] 5014. 스타트링크  (0) 2021.06.20
[BAEKJOON] 1644. 소수의 연속합  (0) 2021.06.17
[BAEKJOON] 11066. 파일 합치기  (0) 2021.06.16
[BAEKJOON] 16234. 인구 이동  (0) 2021.06.16
[BAEKJOON] 1937. 욕심쟁이 판다  (0) 2021.06.14