C++实现简单走迷宫的代码

640?wx_fmt=gif

用n*n个小方格代表迷宫,每个方格上有一个字符0或1,0代表这个格子不能走,1代表这个格子可以走。只能一个格子一个走,而且只能从一个格子向它的上、下、左、右四个方向走,且不能重复。迷宫的入口和出口分别位于左上角和右下角,存在唯一的一条路径能够从入口到达出口,试着找出这条路径。

例如,下图是一个迷宫,红色表示走出迷宫的一条路径

640?wx_fmt=jpeg

输入:入口坐标(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;	
}

640?wx_fmt=png

640?wx_fmt=png

它,

不仅仅是一个码

扫码关注

C++资源免费送

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值