题目
X 星的坦克战车很奇怪,它必须交替地穿越正能量辐射区和负能量辐射区才能保持正常运转,否则将报废。
某坦克需要从 A 区到 B 区去( A,B 区本身是安全区,没有正能量或负能量特征),怎样走才能路径最短?
已知的地图是一个方阵,上面用字母标出了 A,B 区,其它区都标了正号或负号分别表示正负能量辐射区。
例如:
A + - + -
- + - - +
- + + + -
+ - + - +
B + - + -
坦克车只能水平或垂直方向上移动到相邻的区。
第一行是一个整数 nn,表示方阵的大小, 4 ≤n<100。
接下来是 nn 行,每行有 nn 个数据,可能是 A,B,+,- 中的某一个,中间用空格分开。A,B 都只出现一次。
输出一个整数,表示坦克从 A 区到 B 区的最少移动步数。
如果没有方案,则输出 -1。
题解:
寻求最少步数,采用bfs;
于‘A’处入栈,‘B’处return;
越界和错误条件
代码:
#include<iostream>
#include<cstring>
#include<queue>
#define x first
#define y second
using namespace std;
int nex[4][2] = { {0,1},{1,0},{-1,0},{0,-1} };
const int N = 1e2 + 10;
int n;
char g[N][N];
int dist[N][N];
typedef pair<int, int>PII;
int bfs()
{
queue<PII>q;
memset(dist, -1, sizeof dist);
for (int i = 0; i < n; i++)
for(int j=0;j<n;j++)
if (g[i][j] == 'A')
{
dist[i][j] = 0;
q.push({ i,j });
}
while (q.size())
{
auto t = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int tx = t.x + nex[i][0], ty = t.y + nex[i][1];
if (tx < 0 || ty < 0 || tx >= n || ty >= n || g[tx][ty] == g[t.x][t.y] || dist[tx][ty] != -1)
continue;
dist[tx][ty] = dist[t.x][t.y] + 1;
if (g[tx][ty] == 'B')
return dist[tx][ty];
q.push({ tx,ty });
}
}
return -1;
}
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; ++j)
cin >> g[i][j];
cout << bfs() << endl;
return 0;
}