-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpractice_BFS_chapter2_page44.cpp
More file actions
74 lines (67 loc) · 1.37 KB
/
Copy pathpractice_BFS_chapter2_page44.cpp
File metadata and controls
74 lines (67 loc) · 1.37 KB
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
#include<cstdio>
#include<queue>
using namespace std;
#define Max_N 101
#define INF 100000000
char map[Max_N][Max_N];// Map
int memo[Max_N][Max_N];// Distance
int N,M;
int x[4] = {-1,1,0,0};//left,right,up,down
int y[4] = {0,0,1,-1};
int sx,sy,gx,gy;
typedef pair<int,int> P;
int bfs(){
queue<P> que;
que.push(P(sx,sy));
while(que.size()){
P p = que.front();
que.pop();
if(p.first == gx && p.second == gy)
break;
for(int i=0;i<4;i++){
int pointer_x = p.first+x[i];
int pointer_y = p.second+y[i];
if(pointer_x>=0&&pointer_x<N&&pointer_y>=0&&pointer_y<N&&memo[pointer_x][pointer_y]==INF&&map[pointer_x][pointer_y]!='#'){
que.push(P(pointer_x,pointer_y));
memo[pointer_x][pointer_y]=memo[p.first][p.second]+1;
}
}
}
return memo[gx][gy];
}
void solve(){
int result = bfs();
printf("%d\n",result);
}
int main(){
int i,j;
char tmp[Max_N];
scanf("%d%d",&N,&M);
for(i=0;i<N;i++){
scanf("%s",tmp);
for(j=0;j<M;j++){
map[i][j]=tmp[j];
if(tmp[j]=='S'){
memo[i][j]=0;
sx=i;
sy=j;
}
else if(tmp[j]=='G'){
memo[i][j]=INF;
gx=i;
gy=j;
}
else{
memo[i][j]=INF;
}
}
}
solve();
// printf("\n");
// for(i=0;i<N;i++){
// for(j=0;j<M;j++){
// printf("%c",map[i][j]);
// }
// printf("\n");
// }
}