-

[BOJ - JAVA] 2178 - 미로탐색(BFS) 본문

백준 문제 풀이

[BOJ - JAVA] 2178 - 미로탐색(BFS)

흣차 2021. 11. 18. 23:51
728x90
반응형

# 주소

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

 

2178번: 미로 탐색

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

www.acmicpc.net

# 문제

# 문제 해설 및 코드 리뷰

import java.util.*;
public class Main {
  static int[] dx = {0, 1, 0, -1}; 
  static int[] dy = {1, 0, -1, 0}; 
  public static int n, m; 
  public static int map[][]; 
  public static boolean visit[][];
  public static void bfs(int x, int y) {
    Queue<Integer> qx = new LinkedList<Integer>(); 
    Queue<Integer> qy = new LinkedList<Integer>(); 
     qx.add(x); 
    qy.add(y); 
    while(!qx.isEmpty() && !qy.isEmpty()) {
      x = qx.poll(); 
      y = qy.poll(); 
      visit[x][y] = true; 
      for(int i = 0; i < 4; i++) {
        int _x = x + dx[i]; 
        int _y = y + dy[i]; 
        if(_x >= 0 && _y >= 0 && _x < n && _y < m) { 
          if(map[_x][_y] == 1 && visit[_x][_y] == false) {
            qx.add(_x); 
            qy.add(_y); 
            visit[_x][_y] = true; map[_x][_y] = map[x][y] + 1;
            }
          } 
        } 
      } 
    } 
    public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    n = sc.nextInt();
    m = sc.nextInt(); 
    map = new int[100][100]; 
    visit = new boolean[100][100]; 
    for(int i = 0; i < n; i++) { 
      String temp = sc.next(); 
        for(int j = 0; j < m; j++) { 
          map[i][j] = temp.charAt(j) - 48; 
          } 
        } 
      bfs(0, 0);
      System.out.println(map[n-1][m-1]); 
    } 
  } 
}
728x90
반응형
Comments