在更新了边权之后,如果当前路的长度为0,那么dist和原来的一样,那么这个就不能推入到队列的末尾中。因为在 bfs
的时候整个队列需要保证 两端性和单调性 。如果让dist没有增加的点放到最后,势必会破坏整个队列的单调性。
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <string>
using namespace std;
const int N = 510, M = N * N, INF = 0x3f3f3f3f;
typedef pair<int, int> pii;
#define xx first
#define yy second
char cs[] = "\\/\\/";
int dx[] = {-1, -1, 1, 1}, dy[] = {-1, 1, 1, -1};
int ix[] = {-1, -1, 0, 0}, iy[] = {-1, 0, 0, -1};
char g[N][N];
int dist[N][N];
bool st[N][N];
int n, m;
bool check(int x, int y)
{
if (x < 0 || y < 0 || x > n || y > m)
return false;
if (st[x][y])
return false;
return true;
}
int bfs()
{
if ((n + m) & 1)
return INF;
memset(dist, 0x3f, sizeof dist);
memset(st, false, sizeof st);
dist[0][0] = 0;
deque<pii> q;
q.push_front({0, 0});
while (q.size())
{
auto t = q.front();
q.pop_front();
if (st[t.xx][t.yy])
continue;
st[t.xx][t.yy] = true;
for (int i = 0; i < 4; i++)
{
int tx = t.xx + dx[i], ty = t.yy + dy[i];
int cx = t.xx + ix[i], cy = t.yy + iy[i];
if (check(tx, ty))
{
int tt = (g[cx][cy] != cs[i]);
dist[tx][ty] = min(dist[tx][ty], dist[t.xx][t.yy] + tt);
if (tt)
q.push_back({tx, ty});
else
q.push_front({tx, ty});
}
}
}
return dist[n][m];
}
int main()
{
int T;
cin >> T;
while (T--)
{
cin >> n >> m;
for (int i = 0; i < n; i++)
cin >> g[i];
int res = bfs();
if (res == INF)
puts("NO SOLUTION");
else
cout << res << endl;
}
return 0;
}