题目描述
蓝桥杯 坦克
算法1
dfs
blablabla
时间复杂度
参考文献
C++ 代码
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 110;
typedef pair<int,int> PII;//队列里放某一个点的xy坐标
int n;
char g[N][N];//存图
int f[N][N];//答案
bool st[N][N];//表示该点是否搜过
int dx[4] ={-1,0,1,0}, dy[4] = {0,1,0,-1};//表示坐标更改的向量数组,代替4个if的写法
int ax,ay,bx,by;
void bfs(int x,int y)
{
f[x][y] = 0;
st[x][y] = true;
queue<PII> q;
q.push({x,y});
//初始化过程(第一个点入队,更新它的状态和答案距离)
while(q.size())
{
auto t = q.front();
q.pop();
for(int i = 0;i < 4;i ++)
{
int tx = t.first + dx[i],ty = t.second + dy[i];
if(tx < 0 || tx >= n || ty <0 || ty >= n || st[tx][ty] ||g[tx][ty]==g[t.first][t.second]) continue;//不满足条件的点直接跳过
//g[tx][ty]==g[t.first][t.second],最重要的条件,交替走+-,不相同就可以了,走到B也是一样满足条件
f[tx][ty] = min(f[tx][ty],f[t.first][t.second] + 1);
q.push({tx,ty});
st[tx][ty] = true;
}
}
}
int main()
{
cin >> n;
for(int i = 0;i < n;i ++ )
for(int j = 0;j < n;j ++ ){
cin >> g[i][j];
if(g[i][j] == 'A') ax = i,ay = j;
if(g[i][j] == 'B') bx = i,by = j;
}//记录AB的坐标,从A开始搜索,f[bx][by]的值就是从A到B的最短路长度
memset(f,0x3f,sizeof f);//初始化为INF,表示还没搜过
bfs(ax,ay);
if(f[bx][by] == 0x3f3f3f3f) cout << -1;
else cout << f[bx][by];
return 0;
}