标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9424 Accepted Submission(s): 4551
3
3 3
2 1 1
1 1 0
1 1 3
4 8
2 1 1 0 1 1 1 0
1 0 4 1 1 0 4 1
1 0 0 0 0 0 0 1
1 1 1 4 1 1 1 3
5 8
1 2 1 1 1 1 1 4
1 0 0 0 1 0 0 1
1 4 1 0 1 1 0 1
1 0 0 0 0 3 0 1
1 1 4 1 1 1 1 1
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <stack> #include <queue> #include <string> const int inf = (1<<31)-1; const int MAXN = 1e1; using namespace std; struct step{ int x; int y; int t; int limit; }; int mov[4][2]={-1,0,1,0,0,1,0,-1}; queue<step>q; char G[MAXN][MAXN]; int dp[MAXN][MAXN]; int n,m; int check(int x,int y){ if(x<0||y<0||x>=n||y>=m)return 0; if(G[x][y]==‘0‘)return 0; else return 1; } void init(){ for(int i=0;i<n;i++){ for(int j=0;j<m;j++) dp[i][j]=inf; } } int main() { int t; int sx,sy; int flag; char ts[3]; scanf("%d",&t); while(t--){ flag = -1; scanf("%d%d",&n,&m); init(); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ scanf("%s",ts); G[i][j] = ts[0]; if(G[i][j]==‘2‘){ sx = i; sy = j; } } } /* printf("debug\n"); for(int i=0;i<n;i++){ printf("%s\n",G[i]); }*/ step tp,fro; tp.x = sx; tp.y = sy; tp.t = 0; tp.limit = 0; q.push(tp); G[sx][sy]=‘1‘; dp[sx][sy]=0; int nx,ny; while(!q.empty()){ fro = q.front(); q.pop(); if(G[fro.x][fro.y]==‘3‘){ flag = fro.t; break; } if(fro.limit>=5)continue; for(int i=0;i<4;i++){ nx = fro.x+mov[i][0]; ny = fro.y+mov[i][1]; if(check(nx,ny)){ if(G[nx][ny]==‘4‘){ tp.limit = 0; }else{ tp.limit = fro.limit+1; } if(tp.limit<dp[nx][ny]){ tp.t = fro.t +1; tp.x = nx; tp.y = ny; q.push(tp); dp[nx][ny] = tp.limit; } } } } while(!q.empty()){ q.pop(); } /*for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ cout<<dp[i][j]<<" "; } cout<<endl; }*/ cout<<flag<<endl; } //cout << "Hello world!" << endl; return 0; } /* 3 3 3 2 1 1 1 1 0 1 1 3 4 8 2 1 1 0 1 1 1 0 1 0 4 1 1 0 4 1 1 0 0 0 0 0 0 1 1 1 1 4 1 1 1 3 5 8 1 2 1 1 1 1 1 4 1 0 0 0 1 0 0 1 1 4 1 0 1 1 0 1 1 0 0 0 0 3 0 1 1 1 4 1 1 1 1 1 */
标签:
原文地址:http://www.cnblogs.com/EdsonLin/p/5436026.html