自动规划路径
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
struct node {
int x,y,fx,fy;
int g,h,f;
int setG(int ff) {
int sum = abs(fx - x) + abs(fy - y);
if(sum == 2) return ff + 14;
else return ff + 10;
}
int setH(node ee) {
return (abs(x - ee.x) + abs(y - ee.y)) * 10;
}
};
vector <node> open,close;
node ss,ee;
int n;
char mp[N][N];
bool st[N][N],flag;
int dx[8] = {-1,-1,-1,0,0,1,1,1},dy[8] = {-1,0,1,-1,1,-1,0,1};
ifstream ifl;
void bfs () {
ss.g = 0,ss.h = (abs(ss.x - ee.x) + abs(ss.y - ee.y)) * 10;
ss.f = ss.g + ss.h;
open.push_back(ss);
while(1){
// 找到 open 列表里 f 值最小的点计算其周围点的 f 值
node tp;
int F = 0x3f3f3f3f,idx = -1;
for(int i = 0; i < open.size(); i++){
if(!st[open[i].x][open[i].y] && F > open[i].f)
F = open[i].f,idx = i;
}
if(idx == -1) return ;
tp = open[idx];
st[tp.x][tp.y] = 1; //标记掉
close.push_back(tp);
for(int i = 0; i < 8; i++) {// 处理八个方向
int xx = tp.x + dx[i], yy = tp.y + dy[i];
if(!st[xx][yy] && mp[xx][yy] != '#' && xx >= 1 && yy <= n && yy >= 1 && xx <= n){ // 如果没有搜索过
node tp2;
tp2.x = xx,tp2.y = yy,tp2.fx = tp.x,tp2.fy = tp.y; // 记录该点坐标以及父节点坐标
tp2.g = tp2.setG(tp.g),tp2.h = tp2.setH(ee);
tp2.f = tp2.g + tp2.h;
open.push_back(tp2);
if(tp2.x == ee.x && tp2.y == ee.y){
ee.fx = tp2.fx,ee.fy = tp2.fy;
flag = true;
return ;
}
}
}
}
}
int main() {
ifl.open("test1.txt",ios::in);
cin >> n;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++) {
cin >> mp[i][j];
if(mp[i][j] == 's') ss.x = i,ss.y = j;
if(mp[i][j] == 'e') ee.x = i,ee.y = j;
}
bfs();
if(flag){
int xx = ee.fx,yy = ee.fy,s = close.size();
//cout << close.size() << endl;
while(s--){
for(int i = 0; i < close.size(); i++){
// cout << close[i].x << " " << xx << endl;
// cout << close[i].y << " " << yy << endl;
if(close[i].x = xx && close[i].y == yy){
// cout << xx << " " << yy << endl;
mp[xx][yy] = '*';
xx = close[i].fx,yy = close[i].fy;
}
}
if(xx == ss.x && yy == ss.y)
break;
}
mp[ss.x][ss.y] = 's';
cout << "搜索结果为:" << endl;
for(int i = 0; i <= 2*n + 2; i++)
cout << '-';
cout << endl;
for(int i = 1; i <= n; i++) {
cout << "| ";
for(int j = 1; j <= n; j++)
cout << mp[i][j] << " ";
cout << "|" << endl;
}
for(int i = 0; i <= 2*n + 2; i++)
cout << '-';
cout << endl;
}
else cout << "There is no way !" << endl;
return 0;
}