搜索效果
C#项目文件可以点击下载
搜索最短路径的代码:
/// <summary> ///DFS求最短路径 /// </summary> /// <param name="cX">当前点X坐标</param> /// <param name="cY">当前点Y坐标</param> /// <param name="setpNumber">达到当前点的步数</param> /// <returns>是否找到路径</returns> public bool SearchShortPath(int cX, int cY,uint setpNumber) { TotalSetp++; //搜索总次数记录 bool rtn = false;//最终搜索的结果,是否找到路径 bool rst = false;//已经找到路径标记 if (setpNumber < MapStep[cX, cY])//MapStep中存储的是到达该点的最小步数 { MapStep[cX, cY] = setpNumber; if (cX == PTarget.X && cY == PTarget.Y) {//PTarget是目标点 ShortBrights = (bool[,])Brights.Clone(); } } else { return false;//如果之前到过这个点,并且步数比这次少,则直接返回 } //到点标记 Brights[cX, cY] = true; //判断是否到终点 if (cX == PTarget.X && cY == PTarget.Y) { return true; } if (ShowProcess) {//用于界面显示,与计算无关 if (TimeDelay > 0) { Show(); Thread.Sleep(TimeDelay); } } //向左搜索 int nextX = cX - 1; int nextY = cY; if (IsReachable(nextX, nextY))//IsReachable()判断该点是否可以到达,在地图范围内,且不为阻碍则可以到达 { rst = SearchShortPath(nextX, nextY, ++setpNumber); Brights[nextX, nextY] = false; //到点标记置为FALSE setpNumber--; } if (rst) { rtn= true; } //向右搜索 nextX = cX + 1; nextY = cY; if (IsReachable(nextX, nextY)) { rst = SearchShortPath(nextX, nextY, ++setpNumber); Brights[nextX, nextY] = false; setpNumber--; } if (rst) { rtn= true; } //向上搜索 nextX = cX; nextY = cY - 1; if (IsReachable(nextX, nextY)) { rst = SearchShortPath(nextX, nextY,++setpNumber); Brights[nextX, nextY] = false; setpNumber--; } if (rst) { rtn= true; } //向下搜索 nextX = cX; nextY = cY + 1; if (IsReachable(nextX, nextY)) { rst = SearchShortPath(nextX, nextY, ++setpNumber); Brights[nextX, nextY] = false; setpNumber--; } if (rst) { rtn = true; } return rtn; }
标签:C#,路径,DFS,setpNumber,cY,cX,rst,nextX,nextY From: https://www.cnblogs.com/lt33/p/16818590.html