标签:
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
4 -1 13
分析:这是一道简单的BFS问题,与以往不同的是这道题可以去重复的路,我刚开始想的是去重问题怎么解决,后来上网看了别人的博客,只需去掉不可能的路线即可,
我的代码:
#include<iostream>
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
int dx[]={0,1,-1,0};
int dy[]={1,0,0,-1};
struct node
{
int x,y;
int time;
int step;
};
int m,n;
int vis[1000][1000];
inline bool in(node gx)
{
if(gx.x>=0&&gx.x<n&&gx.y>=0&&gx.y<m)
return true;
return false;
}
int main()
{
int test;
node gx;
cin>>test;
while(test--)
{
cin>>n>>m;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
cin>>vis[i][j];
if(vis[i][j]==2)
{
gx.x=i;
gx.y=j;
gx.time=6;
gx.step=0;
}
}
queue<node> q;
while(!q.empty()) q.pop();
q.push(gx);
node next,tmp;
int sp=0;
while(!q.empty())
{
tmp=q.front(),q.pop();
if(tmp.time==1) //去掉不可能的路线
continue;
for(int i=0;i<4;i++)
{
next.x=tmp.x+dx[i];
next.y=tmp.y+dy[i];
if(vis[next.x][next.y]&&in(next))
{
next.time=tmp.time-1;
next.step=tmp.step+1;
if(vis[next.x][next.y]==4)
{
next.time=6;
vis[next.x][next.y]=0;
}
q.push(next);
}
if(vis[next.x][next.y]==3)
{
sp=next.step;
break;
}
}
if(sp>0)
break;
}
if(sp)
printf("%d\n",sp);
else
printf("-1\n");
}
return 0;
}
标签:
原文地址:http://blog.csdn.net/qq_qingtian/article/details/43907053