Java | 미로 탐색 [백준 2178]

나경호·2022년 4월 10일
0

알고리즘 Algorithm

목록 보기
88/106

미로 탐색

출처 | 미로 탐색 [백준 2178]

문제

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

101011
101010
101011
111011

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

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

입력

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

출력

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


풀이

import java.io.*;
import java.util.*;

class Node {
    int x;
    int y;

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

    public int getX() {
        return this.x;
    }
    public int getY() {
        return this.y;
    }
}

public class Main{
    public static int N, M;
    public static int [][] graph = new int[101][101];
    public static int [] dx = {-1, 1, 0, 0};
    public static int [] dy = {0, 0, -1, 1};
    
    public static int bfs(int x, int y) {
        Queue<Node> q = new LinkedList<>();
        q.offer(new Node(x, y));
        while (!q.isEmpty()) {
            Node node = q.poll();
            x = node.getX();
            y = node.getY();
            for (int i = 0; i < 4; i++) {
                int nx = x + dx[i];
                int ny = y + dy[i];
                if (nx < 0 || nx > M || ny < 0 || ny > N) {
                    continue;
                }
                if (graph[ny][nx] == 0) {
                    continue;
                }
                if (graph[ny][nx] == 1) {
                    graph[ny][nx] = graph[y][x] + 1;
                    q.offer(new Node(nx, ny));
                }
            }
        }
        return graph[N - 1][M - 1];    
    }
    

    
	public static void main(String[] args) throws IOException{

        BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));

        StringTokenizer st = new StringTokenizer(scan.readLine());
        
        N = Integer.parseInt(st.nextToken()); 
        M = Integer.parseInt(st.nextToken());  
        

        //graph 구성
        for(int y = 0; y < N; y++){
            String map = scan.readLine();
            for(int x = 0; x < M; x++) {
                graph[y][x] = map.charAt(x) - '0'; 
            }
        }
        
        System.out.print(bfs(0, 0));
    }
}

출처

알고리즘 분류

profile
기억창고👩‍🌾

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN