http://acm.hdu.edu.cn/showproblem.php?pid=5335
这是15年多校赛的一道题,很容易想到是BFS,但是却有很多细节有待讨论。
首先,我们要明白我们最好肯定是走0的地方,如果0可以直接到终点那就更好了。所以,如果左上角是0,我们用bfs每个点朝着四个方向跑一遍图,看看是否有一条全为0的路到达右下角。
其次,如果不存在这样一条路,我们的起点应该设置为bfs 0 的时候能到达的1且离右下角曼哈顿距离最小的点。
最后要说的是,你多一位肯定就比其他点要大,所以你再bfs的时候,只能向右或者向下走。
然后就是怎么去实现上面这些操作了。我一开始有很多细节的地方没想到所以一直wa,wa了十余发,最后找了网上别人代码跑了一边随机的数据和我的对比一下才明白哪里写错了。
代码如下:
#include<bits/stdc++.h>
using namespace std;
char G[1005][1005];
int vst[1005][1005];
int n, m;
int dir[][2] = {0,1, 1,0, 0,-1, -1,0};
int dis[2015];
struct node
{
int x, y;
node(){}
node(int a, int b)
{
x = a;
y = b;
}
};
bool Check(node t)
{
if(t.x >= 0 && t.x < n && t.y >= 0 && t.y < m && !vst[t.x][t.y])
return 1;
return 0;
}
void print(int Max)
{
for(int i = Max; i <= n + m - 2; i++)
printf("%d", dis[i]);
printf("\n");
}
void bfs()
{
for(int i = 0; i < 2005; i++)
dis[i] = 10000;
memset(vst, 0, sizeof(vst));
queue <node> q;
vector <node> v;
node now, next;
now.x = 0;
now.y = 0;
vst[0][0] = 1;
int Max = 0;
if(G[0][0] == '0')
{
q.push(now);
while(!q.empty())
{
now = q.front();
q.pop();
if(now.x == n - 1 && now.y == m - 1)
{
cout << "0" << endl;
return;
}
for(int i = 0; i < 4; i++)
{
next.x = now.x + dir[i][0];
next.y = now.y + dir[i][1];
if(Check(next))
{
vst[next.x][next.y] = 1;
if(G[next.x][next.y] == '0')
q.push(next);
else
{
v.push_back(next);
Max = max(Max, next.x + next.y);
}
}
}
}
for(int i = 0; i < v.size(); i++)
{
now = v[i];
if(now.x + now.y == Max)
q.push(now);
}
}
else
q.push(now);
dis[Max] = 1;
while(!q.empty())
{
now = q.front();
q.pop();
// cout << now.x << " " << now.y << endl;
if(G[now.x][now.y] - 48 != dis[now.x + now.y])
continue;
if(now.x == n - 1 && now.y == m - 1)
{
print(Max);
return;
}
for(int i = 0; i < 2; i++)
{
next.x = now.x + dir[i][0];
next.y = now.y + dir[i][1];
if(Check(next))
{
dis[next.x + next.y] = min(dis[next.x + next.y], G[next.x][next.y] - 48);
q.push(next);
vst[next.x][next.y] = 1;
}
}
}
}
int main()
{
int T;
cin >> T;
while(T--)
{
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i++)
scanf("%s", &G[i]);
bfs();
}
return 0;
}