Problem Description
In an
n∗m maze, the right-bottom corner is the exit (position
(n,m) is the exit). In every position of this maze, there is either a
0 or a
1 written on it. An explorer gets lost in this grid. His position now is
(1,1), and he wants to go to the exit. Since to arrive at the exit is easy for him, he wants to do something more difficult. At first, he'll write down the number on position
(1,1). Every time, he could make a move to one adjacent position (two positions are adjacent if and only if they share an edge). While walking, he will write down the number on the position he's on to the end of his number. When finished, he will get a binary number. Please determine the minimum value of this number in binary system.
Input
The first line of the input is a single integer
T (T=10), indicating the number of testcases. For each testcase, the first line contains two integers
n and
m (1≤n,m≤1000). The
i-th line of the next
n lines contains one 01 string of length
m, which represents
i-th row of the maze.
Output
For each testcase, print the answer in binary system. Please eliminate all the preceding
0 unless the answer itself is
0 (in this case, print
0 instead).
Sample Input
2 2 2 11 11 3 3 001 111 101
Sample Output
111
101
先用dfs推断最远的0能够到达的位置。然后依照斜行递推
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<algorithm>
#include<string>
#pragma comment(linker, "/STACK:102400000,102400000")
typedef long long ll;
using namespace std;
const ll maxn=1005;
int T,n,m,f[maxn][maxn],c[maxn][maxn],tot;
char s[maxn][maxn];
void dfs(int x,int y)
{
if (c[x][y]) return ;
c[x][y]=1;
if (s[x][y]=='1') return;
f[x][y]=1;
if(x+y>tot) tot=x+y;
if (x>1) dfs(x-1,y);
if (x<n) dfs(x+1,y);
if (y>1) dfs(x,y-1);
if (y<m) dfs(x,y+1);
}
int main()
{
scanf("%d",&T);
while (T--)
{
memset(f,0,sizeof(f));
memset(c,0,sizeof(c));
scanf("%d%d",&n,&m);
tot=1;
for (int i=1;i<=n;i++)
{
scanf("%s",s[i]+1);
}
dfs(1,1);
if(tot==n+m)
{printf("0\n");continue;}
if(tot==1)
{
tot=2;
f[1][1]=1;
printf("%d",1);
}
for (int i=tot;i<n+m;i++)
{
int flag=1;
for (int j=max(1,i-m);j<=min(n,i-1);j++)
if (f[j][i-j])
{
int x=j<n?s[j+1][i-j]-'0':1;
int y=i-j<m?s[j][i-j+1]-'0':1;
flag=min(flag,min(x,y));
}
for (int j=max(1,i-m);j<=min(n,i-1);j++)
if (f[j][i-j])
{
int x=j<n?
s[j+1][i-j]-'0':1; int y=i-j<m?s[j][i-j+1]-'0':1; if (x==flag) f[j+1][i-j]=1; if (y==flag) f[j][i-j+1]=1; } printf("%d",flag); } printf("\n"); } return 0; }