미로 탐색(2178)
풀이
- 상하 좌우를 살피면서 bfs를 통해 이동한 횟수를 적어주고 목적지까지의 이동한 횟수를 출력해주면 된다.
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
class Point{
int x;
int y;
public Point(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 {
static int arr[][];
static boolean visited[][];
static int dx[] = {0, 0, -1, 1}; // 상, 하, 좌, 우
static int dy[] = {-1, 1, -0, 0,};
static int distance[][];
public static void main(String args[]) throws IOException {
FastScanner sc = new FastScanner();
int n = sc.nextInt(); // 세로
int m = sc.nextInt(); // 가로
arr = new int[n][m];
visited = new boolean[n][m];
distance = new int[n][m];
for(int i=0; i<n; i++){
String str = sc.next();
for(int j=0; j<m; j++)
arr[i][j] = str.charAt(j) - '0';
}
bfs(n, m);
System.out.println(distance[n-1][m-1]);
}
public static void bfs(int n, int m) {
Queue<Point> queue = new LinkedList<>();
queue.add(new Point(0,0));
visited[0][0] = true;
distance[0][0] = 1;
while(!queue.isEmpty()){
Point cur = queue.poll();
for(int i=0; i<4; i++) {
int nextX = cur.getX() + dx[i];
int nextY = cur.getY() + dy[i];
if(nextX >= 0 && nextX <m && nextY >=0 && nextY < n && !visited[nextY][nextX] && arr[nextY][nextX] == 1){
distance[nextY][nextX] = distance[cur.getY()][cur.getX()] + 1;
visited[nextY][nextX] = true;
queue.add(new Point(nextX,nextY));
}
}
}
}
}