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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | import java.util.ArrayList; import java.util.Scanner; import java.awt.Point; import java.io.FileInputStream; class Solution { static int n; static int m; static int[][] map; static int[][] visited; static ArrayList<Point> queue; public static void main(String args[]) throws Exception { // Scanner sc = new Scanner(new FileInputStream("sample_input.txt")); Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); map = new int[n][m]; sc.nextLine(); for (int i = 0; i < n; i++) { String line = sc.nextLine(); for (int j = 0; j < m; j++) { map[i][j] = Integer.parseInt(line.substring(j, j + 1)); } } visited = new int[n][m]; queue = new ArrayList<Point>(); BFS(0, 0); } // main static void BFS(int x, int y) { int[] move_x = { 1, -1, 0, 0 }; int[] move_y = { 0, 0, 1, -1 }; int level = 1; visited[x][y] = 1; queue.add(new Point(x, y)); while (queue.isEmpty() != true) { int queue_size = queue.size(); for (int i = 0; i < queue_size; i++) { int curr_x = queue.get(0).x; int curr_y = queue.get(0).y; queue.remove(0); for (int j = 0; j < 4; j++) { int next_x = move_x[j] + curr_x; int next_y = move_y[j] + curr_y; if (next_x < n && next_y < m && next_x >= 0 && next_y >= 0) { if (map[next_x][next_y] == 1 && visited[next_x][next_y] == 0) { visited[next_x][next_y] = 1; queue.add(new Point(next_x, next_y)); if (next_x == n - 1 && next_y == m - 1) { System.out.println(level + 1); break; } } } } } // queue_size for level++; } // while } // BFS } | cs |
'공부 > 알고리즘문제' 카테고리의 다른 글
백준 14500 테트로미노 (0) | 2017.04.24 |
---|---|
백준 7562 나이트의 이동 (0) | 2017.04.15 |
백준 2644 촌수계산 (0) | 2017.04.15 |
백준 1260 DFS와 BFS (0) | 2017.04.15 |
백준 1012 유기농 배추 (0) | 2017.04.13 |