题解:使用BFS,唯一有一点不同的是这个访问过的点可以重复访问
题目中可以重复访问节点,如果不加以限制就会陷入大量重复访问。
虽然可以重复访问一个位置,但是加上时间的维度,不能重复访问了。
因为在时间上重复访问并不能得到更优的解或是本没有解进而可以找到解。
如果不加这个限制呢?肯定超时了,交上去只有20分。
附上代码:
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
const int maxn=150;
int l[maxn][maxn],r[maxn][maxn];
int vis[maxn][maxn][300];
int nnext[][2]={{0,1},{1,0},{0,-1},{-1,0}};
int n,m,t;
struct node{
int r,c,t;
};
bool legal(int a,int b)
{
if(a>=1&&b>=1&&a<=n&&b<=m){
return 1;
}else{
return 0;
}
}
int main()
{
scanf("%d%d%d",&n,&m,&t);
int x,y;
for(int i=1;i<=t;i++){
scanf("%d%d",&x,&y);
scanf("%d%d",&l[x][y],&r[x][y]);
}
node temp;
temp.r=1;
temp.c=1;
temp.t=0;
queue<node>q;
vis[1][1][0]=1;
q.push(temp);
while(!q.empty()){
node top=q.front();
q.pop();
if(top.r==n&&top.c==m){
printf("%d\n",top.t);
break;
}
for(int i=0;i<4;i++){
int nowr=top.r+nnext[i][0];
int nowc=top.c+nnext[i][1];
int nowt=top.t+1;
if(legal(nowr,nowc)&&(nowt<l[nowr][nowc]||nowt>r[nowr][nowc])&&!vis[nowr][nowc][nowt]){
temp.r=nowr;
temp.c=nowc;
temp.t=nowt;
vis[temp.r][temp.c][temp.t]=1;
q.push(temp);
}
}
}
return 0;
}