自动规划路径实验
自动规划路径
#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; }
本文作者:伍六柒-
本文链接:https://www.cnblogs.com/paper-plane/p/15459310.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】