题目描述
题目分析
最短步数问题,采用BFS算法即可。
我的代码
#include <iostream>
#include <algorithm>
#include <queue>
#include <cmath>
using namespace std;
int n;
int ans;
int flag;
const int max_n = 102;
char map[max_n][max_n];
int sign[max_n][max_n];
int a[4] = {-1,0,1,0 };
int b[4] = { 0,1,0,-1};
queue<pair<int,int>> Q;
void BFS(){while(!Q.empty()){int x = (Q.front()).first;int y = (Q.front()).second;for(int i = 0; i <= 3;i++){int nx = x + a[i];int ny = y + b[i];if(map[nx][ny] != map[x][y] && sign[nx][ny] == 0){sign[nx][ny] = sign[x][y] + 1;pair<int,int> P(nx,ny);Q.push(P);}if(map[nx][ny] == 'B'){ans = min(ans,sign[x][y]);}}Q.pop();}return;
}
int main() {char fill;/*初始化*/cin >> n;for(int i = 1; i <= n; i++) {for(int j = 1; j <= n; j++){cin >> map[i][j];sign[i][j] = 0;}}//地图填充 for(int i = 0; i <= n; i++) {map[i][0] = 'e';map[0][i] = 'e';map[n+1][i] = 'e';map[i][n+1] = 'e';sign[i][0] = 1;sign[0][i] = 1;sign[n+1][i] = 1;sign[i][n+1] = 1;}//边缘填充 /*广度优先搜索*/for(int i = 1; i <= n; i++) {for(int j = 1; j <= n; j++){if(map[i][j] == 'A'){sign[i][j] = 1;pair<int,int> P(i,j);Q.push(P);ans = 1000000;BFS();}}}cout<<ans;return 0;
}
第一次在Dev-Cpp上写算法题,相较VS需要更多的细心检测和语法熟练度。