Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

코드와이

[BAEKJOON] 2665. 미로 만들기 본문

acmicpc

[BAEKJOON] 2665. 미로 만들기

코드와이 2021. 10. 16. 21:42

 

문제링크

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

 

2665번: 미로만들기

첫 줄에는 한 줄에 들어가는 방의 수 n(1 ≤ n ≤ 50)이 주어지고, 다음 n개의 줄의 각 줄마다 0과 1이 이루어진 길이가 n인 수열이 주어진다. 0은 검은 방, 1은 흰 방을 나타낸다.

www.acmicpc.net

 

package acmicpc.Gold4;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;

public class 미로만들기 {

	static int n, map[][], dist[][];
	static int[] dr = {-1,1,0,0};
	static int[] dc = {0,0,-1,1};
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		n = Integer.parseInt(br.readLine());
		map = new int[n][n];
		dist = new int[n][n];
		for(int i = 0 ; i < n ; i++) {
			String s = br.readLine();
			
			for(int j = 0 ; j < n ; j++) {
				map[i][j] = s.charAt(j) - '0';
				dist[i][j] = Integer.MAX_VALUE;
			}
		}
		
		dist[0][0] = 0;
		go(0);
		
		System.out.println(dist[n-1][n-1]);
		
	}
	
	public static void go(int x) {
		
		Queue<int[]> queue = new LinkedList<>();
		queue.add(new int[] {0,0});
		
		while(!queue.isEmpty()) {
			
			int[] q = queue.poll();
			
			for(int d = 0 ; d < 4 ; d++) {
				int nr = q[0] + dr[d];
				int nc = q[1] + dc[d];
				
				if(nr < 0 || nc < 0 || nr >= n || nc >= n) continue;
				if(dist[q[0]][q[1]] >= dist[nr][nc]) continue;
				
				queue.add(new int[] {nr,nc});
				
				if(map[nr][nc] == 1) dist[nr][nc] = dist[q[0]][q[1]];
				else dist[nr][nc] = dist[q[0]][q[1]] + 1;
			}
		}
		
	}
	
}

'acmicpc' 카테고리의 다른 글

[BAEKJOON] 1918. 후위 표기식  (0) 2021.10.24
[BAEKJOON] 1167. 트리의 지름  (0) 2021.10.18
[BAEKJOON] 17406. 배열 돌리기4  (0) 2021.10.16
[BAEKJOON] 10775. 공항  (0) 2021.10.10
[BAEKJOON] 4386. 별자리 만들기  (0) 2021.10.10