这是一道简单的bfs题,但是我在上面浪费了很多的时间,主要原因是忽略了最大穿越数的限制。
这道题相当于在普通的bfs上面又加上了一个条件,因此需要特殊处理一种条件相同,另一种状态的情况,设两种状态分别为 a, b
(上一步的下标为1, 下一步的下标为2)
如果 a1 == a2-1 但是 b1 < b2-1 的话可以把 b2改为 b1+1。
大意如此,具体请看代码中的处理。
#include <iostream>
#include <algorithm>#include <string>
#include <stack>
#include <queue>
#include <cstring>
#include <cstdio>
using namespace std;
int mp[30][30], web[30][30], yc[30][30], mstp, sx, sy;
int bfs(pair<int, int> ed)
{
web[1][1] = 0;
queue<pair<int, int> > qe;
qe.push(make_pair(1, 1));
while(!qe.empty())
{
pair<int, int> temp=qe.front();
int stp = web[temp.first][temp.second];
if(temp == ed)
return stp;
++stp;
qe.pop();
for(int i = -1; i <= 1; ++i)
{
for(int j = -1; j <= 1; ++j)
{
if(abs(i) ^ abs(j))
{
if(i + temp.first >= 1 && i + temp.first <= sx && j + temp.second >= 1 && j + temp.second <= sy)
{
if(web[temp.first+i][temp.second+j] == 0 || web[temp.first+i][temp.second+j] > stp){
if(!mp[temp.first+i][temp.second+j] || yc[temp.first][temp.second] < mstp)
{
web[temp.first+i][temp.second+j] = stp;
if(mp[temp.first+i][temp.second+j])
yc[temp.first+i][temp.second+j] = yc[temp.first][temp.second] + 1;
if(make_pair(temp.first+i, temp.second+j) == ed)
return stp;
qe.push(make_pair(temp.first+i, temp.second+j));
}
}
//
if(web[temp.first+i][temp.second+j] == stp && mp[temp.first+i][temp.second+j] && yc[temp.first+i][temp.second+j] > yc[temp.first][temp.second] + 1 ){
yc[temp.first+i][temp.second+j] = yc[temp.first][temp.second] + 1;
}
}
}
}
}
}
return -1;
}
int main()
{
//InIt
int t = 1;
scanf("%d", &t);
while(t--)
{
memset(web, 0, sizeof(web));
memset(yc, 0, sizeof(yc));
memset(mp, 0, sizeof(mp));
scanf("%d %d", &sx, &sy);
scanf("%d", &mstp);
for(int i = 1; i <= sx; ++i)
for(int j = 1; j <= sy; ++j)
scanf("%d", &mp[i][j]);
printf("%d\n", bfs(make_pair(sx, sy)));
// for(int i = 1; i <= sx; ++i)
// for(int j = 1; j <= sy; ++j)
// {
// printf("%d ", web[i][j]);
// if(j == sy)
// printf("\n");
// }
// for(int i = 1; i <= sx; ++i)
// for(int j = 1; j <= sy; ++j)
// {
// printf("%d ", yc[i][j]);
// if(j == sy)
// printf("\n");
// }
}
return 0;
}