C++实现简单走迷宫的代码
生活随笔
收集整理的這篇文章主要介紹了
C++实现简单走迷宫的代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用n*n個小方格代表迷宮,每個方格上有一個字符0或1,0代表這個格子不能走,1代表這個格子可以走。只能一個格子一個走,而且只能從一個格子向它的上、下、左、右四個方向走,且不能重復。迷宮的入口和出口分別位于左上角和右下角,存在唯一的一條路徑能夠從入口到達出口,試著找出這條路徑。
例如,下圖是一個迷宮,紅色表示走出迷宮的一條路徑
輸入:入口坐標(startX,startY),出口坐標(endX,endY)
思路:利用回溯法求解。
代碼實現如下:
#include <iostream> #include <vector> using namespace std; class Solution { public: bool hasPath(char* matrix, int rows, int cols, int startX,int startY, int endX, int endY,vector<int>& Path) { if (matrix == NULL || rows < 1 || cols < 1 || startX<0||startY<0||endX<0||endY<0||(startX==endX&&startY==endY)) return false; bool* visited = new bool[rows*cols]; //定義一個輔助矩陣,用來標記路徑是否已經進入了每個格子 memset(visited, 0, rows*cols); int pathLength = 0; if (hasPathCore(matrix, rows, cols, startX, startY, endX, endY, visited, Path)) { return true; } delete[] visited; return false; } /*此函數用來判斷在當前路徑滿足條件下,相鄰格子中是否存在一個格子滿足條件*/ bool hasPathCore(char* matrix, int rows, int cols, int row, int col, int endX, int endY, bool* visited, vector<int>& Path) { if ((row == endX) && (col == endY)&&(matrix[row*cols+col]=='1')) { Path.push_back(endY); Path.push_back(endX); return true; } bool hasPath = false; if (row >= 0 && row < rows&&col >= 0 && col < cols&&matrix[row*cols + col] == '1' && !visited[row*cols + col]) { // ++pathLength; visited[row*cols + col] = true; Path.push_back(col); Path.push_back(row); /*如果矩陣格子(row,col)字符為1時,從它的4個相鄰格子中尋找下一個字符為1的格子*/ hasPath = hasPathCore(matrix, rows, cols, row, col - 1, endX, endY, visited,Path) || hasPathCore(matrix, rows, cols, row - 1, col, endX, endY, visited,Path) || hasPathCore(matrix, rows, cols, row, col + 1, endX, endY, visited,Path) || hasPathCore(matrix, rows, cols, row + 1, col, endX, endY, visited,Path); if (!hasPath) //如果沒找到,則說明當前第n個格子定位不正確,返回上一個位置重新定位 { visited[row*cols + col] = false; Path.pop_back(); Path.pop_back(); } } return hasPath; } }; int main() { // char* matrix = "abcesfcsadee"; char* matrix = "1000000110110001101000010111011110100000010000001"; //設置迷宮 int startX, startY, endX, endY; cin >> startX >> startY >> endX >> endY; //輸入起始結束坐標 Solution s; vector<int> Path; bool re = s.hasPath(matrix, 7, 7, startX,startY,endX,endY,Path); cout << re << endl; for (int i = 0; i < Path.size();) cout << "(" << Path[i++] << ',' << Path[i++] << ")" << " "; cout << endl; return 0; }完
它,
不僅僅是一個碼
掃碼關注
C++資源免費送
總結
以上是生活随笔為你收集整理的C++实现简单走迷宫的代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 达墨狮子座 2230 SSD 2TB 版
- 下一篇: 利用C/C++实现较完整贪吃蛇游戏