[Silver I] 미로 탐색 - 2178

JYC·2024년 1월 10일

[BAEKJOON]

목록 보기
12/102

문제 링크

성능 요약

메모리: 14652 KB, 시간: 132 ms

분류

너비 우선 탐색, 그래프 이론, 그래프 탐색

제출 일자

2024년 1월 11일 07:06:15

문제 설명

N×M크기의 배열로 표현되는 미로가 있다.

1 0 1 1 1 1
1 0 1 0 1 0
1 0 1 0 1 1
1 1 1 0 1 1

미로에서 1은 이동할 수 있는 칸을 나타내고, 0은 이동할 수 없는 칸을 나타낸다. 이러한 미로가 주어졌을 때, (1, 1)에서 출발하여 (N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수를 구하는 프로그램을 작성하시오. 한 칸에서 다른 칸으로 이동할 때, 서로 인접한 칸으로만 이동할 수 있다.

위의 예에서는 15칸을 지나야 (N, M)의 위치로 이동할 수 있다. 칸을 셀 때에는 시작 위치와 도착 위치도 포함한다.

입력

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

출력

첫째 줄에 지나야 하는 최소의 칸 수를 출력한다. 항상 도착위치로 이동할 수 있는 경우만 입력으로 주어진다.

코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
	static int N,M;
	static int[][] map;
	static boolean[][] visited;
	static int[] dx= {1,-1,0,0};
	static int[] dy= {0,0,1,-1};
	static int cnt=1;
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		N= Integer.parseInt(st.nextToken());
		M=Integer.parseInt(st.nextToken());
		map= new int[N][M];
		visited=new boolean[N][M];
		String str;

		for(int i=0;i<N; i++) {
			str=br.readLine();
			for(int j=0; j<M; j++) {
				map[i][j]=str.charAt(j)-'0';
			}
		}
		bfs();
		System.out.println(map[N-1][M-1]);
	}
	static void bfs() {
		var queue = new LinkedList<int[]>();
		queue.add(new int[] {0,0});
		int[] temp = new int[2];
		visited[0][0]=true;
		int y,x;
		int ny,nx;
		while(!queue.isEmpty()) {
			temp=queue.poll();
			y=temp[0];
			x=temp[1];
			for(int i=0; i<4; i++) {
				ny=y+dy[i];
				nx=x+dx[i];
				if(ny<0 || nx<0||ny>=N||nx>=M) {
					continue;
				}
				if(!visited[ny][nx] && map[ny][nx]==1) {
					visited[ny][nx]=true;
					map[ny][nx] += map[y][x];
					queue.add(new int[] {ny,nx});
				}
			}
		}
	}
}
profile
열심히 하기 1일차

0개의 댓글