-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaze_dfs.cpp
More file actions
45 lines (40 loc) · 930 Bytes
/
maze_dfs.cpp
File metadata and controls
45 lines (40 loc) · 930 Bytes
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
#include <iostream>
using namespace std;
int N, M;
char maze[101][101];
int min_length[101][101];
bool visit[101][101];
int fmin = 20000;
int dx[4] = {0, -1, 0, 1};
int dy[4] = {-1, 0, 1, 0};
int dfs(int x, int y, int cnt){
visit[x][y] = true;
if(x == N && y == M){
if(fmin > cnt) fmin = cnt;
visit[x][y] = false;
return 0;
}
for(int i=0; i<4; i++){
int to_x = x + dx[i];
int to_y = y + dy[i];
if(to_x ==0 || to_x == N+1 || to_y == 0 || to_y == M + 1) continue;
if(maze[to_x][to_y]=='0' || visit[to_x][to_y]) continue;
if(min_length[to_x][to_y]!=0 && min_length[to_x][to_y]<=cnt+1) continue;
min_length[to_x][to_y] = cnt+1;
dfs(to_x, to_y, cnt+1);
}
visit[x][y] = false;
return 0;
}
int main(int argc, char* argv[]) {
scanf("%d %d", &N, &M);
for(int i=1; i<=N; i++){
scanf("\n");
for(int j=1; j<=M; j++){
scanf("%c", &maze[i][j]);
}
}
dfs(1, 1, 1);
printf("%d\n", fmin);
return 0;
}