This problem card time card is relatively tight.
At first, the direct BFS no doubt timed out, then thought to choose the starting point to traverse according to the conventional optimization idea of BFS.
So we start with BFS once, this time the BFS is to choose this point for 1 and from the starting point to this point, the middle path point is all 0 points.
By choosing this point, the length of this point to the end of the path can be determined.
After that we put all the points to the lowest point distance in a container for the BFS.
This problem is not made out of the reason is a large part of the BFS understanding is not deep enough and there is no greedy ideas, resulting in this problem without AC.
Well, there's a saying: synthesis is the first productivity.
#include <queue> #include <cstdio> #include <string> #include <cstring> #include <iostream > #include <algorithm>using namespace std;const int maxn = 1005;const int maxd = 1000005;const int INF = (1 <&l T int N,m;char mat[maxn][maxn];const int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};bool vis[maxn][maxn];int min_dist; Vector<int>v0,v1,vv;int path[maxd];int cnt,ok;void bfs_init () {queue<int>q,_q; Q.push (0); Vis[0][0] = true; while (!q.empty ()) {int pos = Q.front (); Q.pop (); int x = pos/m, y = pos% m; if (mat[x][y] = = ' 1 ') {_q.push (POS); min_dist = min (min_dist,n + m-x-y); Continue } if (x = = N-1 && y = = m-1) {OK = 1; Return } for (int i = 0; i < 4; i++) {int _x = x + dir[i][0]; int _y = y + dir[i][1]; if (_x >= 0 && _x < n && _y >= 0 && _y < m&&!vis[_x][_y]) {vis[_x][_y] = true; Q.push (_x * m + _y); }}} while (!_q.empty ()) {int pos = _q.front (); _q.pop (); int x = pos/m, y = pos% m; if ((n + m-x-y) = = min_dist) {vv.push_back (POS); }}}void BFs () {path[0] = 1; for (int i = 1; i < min_dist-1; i++) {int Size = Vv.size (); for (int j = 0; J < Size; J + +) {int x = Vv[j]/m, y = vv[j]% m; for (int d = 0; d < 2; D + +) {int _x = x + dir[d][0]; int _y = y + dir[d][1]; if (_x >= 0 && _x < n && _y >= 0 && _y < m &&!vis[_x][_y]) { Vis[_x][_y] = true; if (mat[_x][_y] = = ' 0 ') v0.push_back (_x * m + _y); else V1.push_back (_x * m + _y); }}} if (V0.empty ()){path[cnt++] = 1; VV = v1; V1.clear (); } else{path[cnt++] = 0; VV = V0; V0.clear (); V1.clear (); }}}void init () {min_dist = INF; memset (vis,false,sizeof (VIS)); V0.clear (); V1.clear (); Vv.clear (); CNT = 1; OK = 0;} int main () {int T; scanf ("%d", &t); while (t--) {scanf ("%d%d", &n,&m); Init (); for (int i = 0; i < n; i++) scanf ("%s", Mat[i]); Bfs_init (); if (OK) printf ("0\n"); else{BFS (); for (int i = 0; i < cnt; i++) printf ("%d", path[i]); Puts (""); }} return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"HDU 5335" Walk Out (BFS)