题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5335
题意:给出一个n*m的矩阵,都是由0和1组成,从(1,1)走到(n,m),每一步的数字组成一个二进制数,问要如何走才可以使得这个数最小
思路:前导0可以被省略,所以一开始可以向4个方向走,直到走到第一个1,走到第一个1后向左和向上走都会使得这个二进制数位数加一,这样一定不是最优解。
我们先用普通的bfs处理前导0,找到一个x+y最大的0(因为这个0离(n,m)最近),然后再以这个点为起点进行第二bfs,第二次bfs为了方便处理,我们使用一个二维数组保存第k和第k+1步数时候的点,如果第k步有点为0的话这一位必定为0,那么第k步为1的点不能再延伸了,如果第k步的点全为1的话需要将所有k+1的点存到s[nxt]里面
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
struct Node
{
int x,y;
};
int t,n,m;
char mp[1030][1030];
int chx[4]= {1,0,-1,0},chy[4]= {0,1,0,-1};
int vis[1030][1030];
queue <Node> que;
vector <Node> s[2];
void bfs()
{
Node now;
now.x=0;
now.y=1;
que.push(now);
int maxx=0;
while (!que.empty())
{
now=que.front();
que.pop();
if (now.x==n && now.y==m)
{
printf("0");
return;
}
if (maxx<now.x+now.y)
{
maxx=now.x+now.y;
s[0].clear();
s[0].push_back(now);
}
else if (maxx==now.x+now.y)
s[0].push_back(now);
for (int i=0; i<4; i++)
{
Node nxt;
int xx=now.x+chx[i];
int yy=now.y+chy[i];
if (xx<=0 || xx>n || yy<=0 || yy>m) continue;
if (vis[xx][yy]==1 || mp[xx][yy]=='1') continue;
vis[xx][yy]=1;
nxt.x=xx;
nxt.y=yy;
que.push(nxt);
}
}
if (s[0].size()==0)
{
Node tmp;
tmp.x=0;
tmp.y=1;
s[0].size();
}
int fir=0,sec=1;
while (true)
{
int flag=1;
for (int i=0; i<s[fir].size(); i++)
{
now=s[fir][i];
if (now.x==n && now.y==m)
{
return;
}
for (int i=0; i<2; i++)
{
Node nxt;
int xx=now.x+chx[i];
int yy=now.y+chy[i];
if (xx<=0 || xx>n || yy<=0 || yy>m) continue;
if (vis[xx][yy]==1) continue;
vis[xx][yy]=1;
nxt.x=xx;
nxt.y=yy;
if (flag && mp[xx][yy]=='0')
{
s[sec].clear();
s[sec].push_back(nxt);
flag=0;
}
if (!flag && mp[xx][yy]=='0')
{
s[sec].push_back(nxt);
}
if (flag && mp[xx][yy]=='1')
{
s[sec].push_back(nxt);
}
}
}
s[fir].clear();
fir=!fir;
sec=!sec;
if (!flag) printf("0");
else printf("1");
}
}
int main()
{
scanf("%d",&t);
while (t--)
{
memset(s,0,sizeof(s));
memset(vis,0,sizeof(vis));
scanf("%d%d",&n,&m);
for (int i=1; i<=n; i++)
scanf("%s",mp[i]+1);
bfs();
printf("\n");
}
}