zoukankan      html  css  js  c++  java
  • 老鼠走迷宫

    #include <iostream>
    #include <time.h>
    #include <stack>
    using namespace std;
    
    int MG[7][7]={{2,2,2,2,2,2,2}, 
    {2,0,0,0,0,0,2}, 
    {2,0,2,0,2,0,2}, 
    {2,0,0,2,0,2,2}, 
    {2,2,0,2,0,2,2}, 
    {2,0,0,0,0,0,2}, 
    {2,2,2,2,2,2,2}};
    
    void printMG()
    {
        for (int i = 0;i <= 6;i++)
        {
            for(int j = 0;j <= 6;j++)
            {
                cout<<MG[i][j]<<" ";
            }
            cout<<endl;
        }
    }
    //全局变量
    stack<int> LJ;//定义一个栈,用于保存路径
    int SPosit[2] = {1,1};//入口位置
    int EPosit[2] = {5,5};//出口位置
    bool state = false;//当前状态,表示是否已经成功
    //检查当前位置是否有效
    bool check(int x,int y)
    {
        if (MG[x][y] == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    void move(int x,int y)
    {
        //将当前点入栈
        LJ.push(x);LJ.push(y);
        MG[x][y] = 1;
        if (!state)
        {
            cout<<"当前位置为("<<x<<","<<y<<")"<<endl;
        }
        if (x == EPosit[0] && y == EPosit[1])
        {//到达出口,输出保存路径
            state = true;
            cout<<"已经到达出口"<<endl;
            cout<<"下面是保存的路径(逆序输出)"<<endl;
            while (!(LJ.empty()))
            {
                cout<<"("<<LJ.top()<<",";
                LJ.pop();
                cout<<LJ.top()<<")"<<"   ";
                LJ.pop();
            }
            cout<<endl;
        }
        else
        {//四个方向上进行递归遍历
            if(check(x-1,y))
            {
                move(x-1,y);
            }
            if (check(x,y+1))
            {
                move(x,y+1);
            }
            if (check(x+1,y))
            {
                move(x+1,y);
            }
            if (check(x,y-1))
            {
                move(x,y-1);
            }
        }
        if (!state)
        {
            //如果在当前点上没有遍历到终点,设置该点位有效点,并且将该点从路径中出栈
            LJ.pop();LJ.pop();
            //MG[x][y] = 0;
        }
    }
    
    
    int main()
    {
        printMG();
        move(SPosit[0],SPosit[1]);
        system("pause");
        return 0;
     }
    迷宫问题

    问题描述:老鼠走迷宫是递回求解的基本题型,我们在二维阵列中使用2表示迷宫墙壁,
                采用一个栈来保存走过的路径,通过适当的入栈出栈,最终得到的就是有效的路径.本算法是一个经典的递归问题

  • 相关阅读:
    Coded UI Test(二)创建一个Coded UI Test
    Coded UI Test(一)概述
    面向接口编程思想与实现可维护的代码 (一)
    KMP算法字符串模式匹配算法
    新的博客,新的起点
    第十三章:字符串 《Thinking in java》学习笔记
    稀疏矩阵三元组表来压缩存储及转置
    eclipse svn的使用+小组开发
    第十一章:持有对象 《Thinking in java》学习笔记
    双端队列(deque)课堂跳了的内容
  • 原文地址:https://www.cnblogs.com/color-my-life/p/3260927.html
Copyright © 2011-2022 走看看