Description
Input
Output
Sample Input
2 2 2 11 11 3 3 001 111 101
Sample Output
111 101
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<queue> #include<vector> using namespace std; const int MAXN = 1000 + 10; struct Node { int x, y; Node() { } Node( int x, int y ) { this->x = x; this->y = y; } }; int vis[MAXN][MAXN]; int zero[MAXN * 4]; //所有x+y的位置上是否存在为0的点 char map[MAXN][MAXN]; int Move[MAXN][MAXN]; //记录路经,方便输出 vector<Node> bg; //所有x+y最大的点 int n, m; int dir[4][2] = { { 0,1 }, { 1,0 }, { -1,0 }, { 0,-1 } }; //移动方向,注意1和4为一对,2和3为一对 void ini() { memset( vis, 0, sizeof vis ); memset( zero, 0, sizeof zero ); memset( Move, -1, sizeof Move ); } bool inline check( int x, int y ) { if(x <= 0 || x > n || y <= 0 || y > m) return false; return true; } void bfs() //找到x+y最远的点 { bg.clear(); bg.push_back( Node (1, 1) ); //此时(1,1)为0,先假设为最远的点 queue<Node> q; q.push( Node( 1, 1 ) ); vis[1][1] = 1; int dis = 1; //最小距离 int x, y; while(!q.empty()) { Node tem = q.front(); q.pop(); x = tem.x; y = tem.y; for(int i = 0; i < 4; i++) { int temx = x + dir[i][0]; int temy = y + dir[i][1]; if(!check( temx, temy ) || map[temx][temy] == '1' || vis[temx][temy]) //如果越界或者是1或者已经找过了就不找了 continue; vis[temx][temy] = 1; q.push( Node( temx, temy ) ); if(temx + temy > dis) //发现更远的点 { dis = temx + temy; bg.clear(); } if(temx + temy == dis) //发现了最远点 { bg.push_back( Node( temx, temy ) ); } } } } void bfs2() //找到从x出发小的数 { queue<Node> q; if(map[1][1] == '1') //如果起点是1,也优先保证数位最短 { q.push( Node( 1, 1 ) ); } else //如果起点是0,则找到第一个1的最远点 { bfs(); for(int i = 0; i < bg.size(); i++) q.push( bg[i] ); } while(!q.empty()) //从第一个1开始,只向右下走 { Node tem = q.front(); q.pop(); int x = tem.x; int y = tem.y; if(map[x][y] == '1'&&zero[x + y]) //如果当前格子为1,但距离同为 x+y 的点有为0的 { continue;//则跳过 } for(int i = 0; i < 2; i++) { int temx = x + dir[i][0]; int temy = y + dir[i][1]; if(!check( temx, temy )) continue; Move[temx][temy] = 3 - i; //记录反方向,方便输出 if(map[temx][temy] == '0') //x+y的点有为0的 zero[temx + temy] = 1; if(!vis[temx][temy]) { vis[temx][temy] = 1; q.push( Node( temx, temy ) ); } } } } int main() { int kase; scanf( "%d", &kase ); while(kase--) { ini(); scanf( "%d%d", &n, &m ); for(int i = 1; i <= n; i++) { scanf( "%s", map[i] + 1 ); } bfs2(); int x = n, y = m; int mtem, cnt = 0; char ans[MAXN * 4]; while(true) //方向走,构造结果 { ans[cnt++] = map[x][y]; mtem = Move[x][y]; if(mtem == -1) break; x = x + dir[mtem][0]; y = y + dir[mtem][1]; } while(cnt&&ans[cnt - 1] == '0') //删除前导〇 cnt--; if(!cnt) { printf( "0\n" ); continue; } for(int i = cnt - 1; i >= 0; i--) { printf( "%c", ans[i] ); } printf( "\n" ); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/maxichu/article/details/48027761