大家好呀!我是一只小苹果!今天我又来写题解了……
如果题解有不对的地方,欢迎大家吐槽指点。
这题有一个坑,那就是 列 行
这个地方输入时这样就可以了↓
int n, m;
... //other codes
cin >> m >> n;接下来是变量的部分,我们需要一个 来记录地形,一个 来避免重复访问,一个 来记录步数, 和 来记录“马”的偏移量,一个 来标记坐标,如下所示↓
int n, m;
char mp[151][151];
bool vis[151][151];
int cnt[151][151];
int dx[8] = {2, 1, -1, -2, -2, -1, 1, 2};
int dy[8] = {1, 2, 2, 1, -1, -2, -2, -1};
struct node{
int x, y;
};接着我们做一个 函数来判断坐标是否合法( 在 1 ~ 之间, 在 1 ~ ,未访问过,不是障碍),如下所示↓
bool check(int x, int y){
if (x < 1 || x > n || y < 1 || y > m || vis[x][y] || mp[x][y] == '*')
return false;
else
return true;
}然后是主体 部分(思路详见代码)↓
void bfs(int x, int y){
queue<node> q;
q.push({x, y});
vis[x][y] = true;
while (!q.empty()){
node f = q.front();
q.pop();
if (mp[f.x][f.y] == 'H'){
cout << cnt[f.x][f.y];
exit(0);
}
for (int i = 0; i < 8; i++){
int tx = f.x + dx[i];
int ty = f.y + dy[i];
if (check(tx, ty)){
q.push({tx, ty});
vis[tx][ty] = true;
cnt[tx][ty] = cnt[f.x][f.y] + 1;
}
}
}
}最后是完整代码↓
#include <bits/stdc++.h>
using namespace std;
int n, m;
char mp[151][151];
bool vis[151][151];
int cnt[151][151];
int dx[8] = {2, 1, -1, -2, -2, -1, 1, 2};
int dy[8] = {1, 2, 2, 1, -1, -2, -2, -1};
struct node{
int x, y;
};
bool check(int x, int y){
if (x < 1 || x > n || y < 1 || y > m || vis[x][y] || mp[x][y] == '*')
return false;
else
return true;
}
void bfs(int x, int y){
queue<node> q;
q.push({x, y});
vis[x][y] = true;
while (!q.empty()){
node f = q.front();
q.pop();
if (mp[f.x][f.y] == 'H'){
cout << cnt[f.x][f.y];
exit(0);
}
for (int i = 0; i < 8; i++){
int tx = f.x + dx[i];
int ty = f.y + dy[i];
if (check(tx, ty)){
q.push({tx, ty});
vis[tx][ty] = true;
cnt[tx][ty] = cnt[f.x][f.y] + 1;
}
}
}
}
int main(){
int sx, sy;
cin >> m >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++){
cin >> mp[i][j];
if (mp[i][j] == 'K')
sx = i, sy = j;
}
bfs(sx, sy);
return 0;
}希望大家更注重解题思路,而非代码本身。