Grid [Gym-100819O] [Problem D]

 1 #include <iostream>
 2 #include <cstdio>
 3 #include<queue>
 4 #include<cstring>
 5 #include <algorithm>
 6 using namespace std;
 7 int G[501][501];
 8 bool vis[501][501];
 9 int dx[4] = {-1,1,0,0};
10 int dy[4] = {0,0,1,-1};
11 typedef struct
12 {
13     int x,y,time;
14 }node;
15 void bfs(int m,int n)
16 {
17     node s;
18     s.x = 0;
19     s.y = 0;
20     s.time = 0;
21     queue<node> q;
22     q.push(s);
23     memset(vis,false,sizeof(vis));
24     vis[0][0] = true;
25     while(!q.empty())
26     {
27         node now = q.front(); q.pop();
28         //printf("%d %d
",now.x,now.y);
29         if(now.x == m-1 && now.y==n-1) {
30             printf("%d",now.time);
31             return;
32         }
33         for(int i=0;i<4;i++)
34         {
35             int nx = now.x + dx[i]*G[now.x][now.y];
36             int ny = now.y + dy[i]*G[now.x][now.y];
37             //printf("-%d %d
",nx,ny);
38             if(nx<0||nx>=m||ny<0||ny>=n||vis[nx][ny]) continue;
39             node nn;
40             nn.x = nx; nn.y = ny; nn.time = now.time+1;
41             q.push(nn);
42             vis[nx][ny] = true;
43         }
44     }
45     printf("IMPOSSIBLE");
46 }
47 
48 int main()
49 {
50     int m,n;cin>>m>>n;
51     for(int i=0;i<m;i++)
52     {
53         string s;
54         cin>>s;
55         int len = s.length();
56         for(int j=0;j<len;j++)
57         {
58             G[i][j] = s[j]-'0';
59         }
60     }
61     //puts("here");
62     bfs(m,n);
63 }
View Code
原文地址:https://www.cnblogs.com/NWUACM/p/6722380.html