走迷宫

这是maze55.txt

5 5
1 1
5 5
0 0 0 0 1
1 1 0 1 1
0 0 0 0 0
1 0 1 0 1
1 0 1 0 0

这是maze.txt

10 10
1 1
10 10
0 0 0 0 0 0 0 0 1 1
0 0 0 0 1 1 1 1 1 1 
1 1 1 0 1 1 1 0 1 1 
0 0 0 0 0 0 0 0 1 1 
1 1 0 1 1 1 1 1 1 1
0 1 0 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0
1 1 0 1 1 0 1 1 1 1
1 1 0 0 0 0 0 0 0 0
1 1 1 0 0 1 1 1 1 0

code

#include<fstream>
#include<iostream>
#include<string>
#include<stack>
#include<queue>
#include<vector>
using namespace std;
const int MaxSize = 12;//迷宫的最大规模
int maze[MaxSize][MaxSize];//迷宫矩阵二维数组
int m, n;//迷宫的行列数
struct node
{
    int x;
    int y;
};
node current_node;//当前点
node next_node;//下一个点
node start_node;//迷宫起点
node end_node;//迷宫终点
stack<node> S;
int  has_nextnode();//在current_node处是否存在可向前的方向
void forward();//在current_node点,向next_node前进一步
void backward();//后退一步
void init_maze()//初始化迷宫矩阵
{
    int i, j;
    string filename = "../maze55.txt";
    ifstream infile(filename);
    infile >> m >> n;
    infile >> start_node.x >> start_node.y;//迷宫起点
    infile >> end_node.x >> end_node.y;//迷宫终点
    for (i = 0; i <= m; i++)//第0行和第n+1行设为障碍
    {
        maze[i][0] = 1;
        maze[i][n + 1] = 1;
    }
    for (j = 0; j <= n; j++)//第0列和第n+1列设为障碍
    {
        maze[0][j] = 1;
        maze[m + 1][j] = 1;
    }
    for (i = 1; i <= m; i++)
    {
        for (j = 1; j <= n; j++)
        {
            infile >> maze[i][j]; //不转置;
            infile >> maze[j][i];//为了和text文档的行列相符合,把矩阵做了一个转置
        }
    }
    infile.close();
}

int  has_nextnode()
{
    for (int i = 0; i <= 3; i++)//判断当前current_node是否可以继续向前
    {
        //next_node.x = current_node.x;
        //next_node.y = current_node.y;
        next_node = current_node;
        switch (i)
        {
        case 0:
            next_node.y--;
            break;
        case 1:
            next_node.x--;
            break;
        case 2:
            next_node.y++;
            break;
        case 3:
            next_node.x++;
            break;
        }
        if (maze[next_node.x][next_node.y] == 0)
            return 1;
    }
    return 0;//不存在可向前的方向
}
void forward()//在current_node点,向next_node前进
{
    S.push(next_node);
    current_node = next_node;
    maze[current_node.x][current_node.y] = 2;
    cout << "前进(" << current_node.x << "," << current_node.y << ")" << endl;
}
void backward()//后退一步
{
    S.pop();
    current_node = S.top();
}

int DFS_maze()//深度优先搜索迷宫的出口
{
    current_node = start_node;
    S.push(current_node);
    maze[current_node.x][current_node.y] = 2;
    while (!S.empty())
    {
        if (has_nextnode())
        {
            forward();
            if (current_node.x == end_node.x && current_node.y == end_node.y)
                return 1;
        }
        else
        {
            backward();
            cout << "后退(" << current_node.x << "," << current_node.y << ")" << endl;
        }
    }
    if (S.empty())
        return 0;
}
int main()
{
    init_maze();
    DFS_maze();
}
 
原文地址:https://www.cnblogs.com/xxxsans/p/13930576.html