1、将连续的时间离散化,在矩阵中增加一维来标记时间。
2、由于本题是要求 最快 到达(n,m)的时间,因此用bfs。点击此处查看 dfs与bfs的区别
代码如下
#include<iostream>
#include<queue>
#include<cstdio>
using namespace std;
int n,m,vis[105][105][1005];
struct node{
int x,y,time;
};
struct POS{
int x,y;
}pos[4]={{-1,0},{1,0},{0,-1},{0,1}};
int bfs(){
node tmp;
queue<node> q;
q.push({1,1,0});
while(!q.empty()){
node p = q.front();
q.pop();
if(p.x==n && p.y==m) return p.time;
for(int i = 0; i < 4; i++){
tmp.x = p.x + pos[i].x;
tmp.y = p.y + pos[i].y;
tmp.time = p.time+1;
if(tmp.x<1||tmp.x>n||tmp.y<1||tmp.y>m||vis[tmp.x][tmp.y][tmp.time]) continue;
vis[tmp.x][tmp.y][tmp.time] = true;
q.push(tmp);
}
}
return 0;
}
int main()
{
int t,r,c,a,b;
scanf("%d%d%d", &n, &m, &t);
for(int i = 0; i < t; i++){
scanf("%d%d%d%d", &r,&c,&a,&b);
for(int j = a; j <= b; j++){
vis[r][c][j] = true;
}
}
printf("%d\n", bfs());
return 0;
}