zoukankan      html  css  js  c++  java
  • 迷宫求解

    任务:可以输入一个任意大小的迷宫数据,用非递归的方法求出一条走出迷宫的路径,并将路径输出;

    #include <iostream>

    #include <stack>

    using namespace std;

    #define N 100

    typedef struct vex{  

      int x;

      int y;

    }vex;

    int n, m;

    stack <vex> s;

    int visited[N+1][N+1];

    int map[N+1][N+1];

    vex a, b, c, d;

    int dir[4][2] = {1,0,0,1,-1,0,0,-1};

    int main()

    {  

      int i, j;  

      int x, y;  

      stack <vex> Q;  

      while (!s.empty())  

      {

        s.pop();  

      }  

      cout<<"请输入迷宫的大小(0代表能走通,1代表不能走通):";  

      cin>>n>>m;  

      for (i=0; i<n; i++)   

        for (j=0; j<m; j++)   

        {

          cin>>map[i][j];    

          visited[i][j] = 0;   

        }  

      cout<<"请输入起点坐标和终点坐标:";

      loop:cin>>a.x>>a.y>>b.x>>b.y;  

      d = a;  

      if (map[a.x-1][a.y-1]!=0 || map[b.x-1][b.y-1]!=0)  

      {

        cout<<"输入的坐标无效,请重新输入"<<endl;   

        goto loop;  

      }  

      s.push(a);  

      visited[a.x-1][a.y-1] = 1;  

      while (!s.empty())  

      {   

        d = s.top();  

        if (d.x==b.x && d.y==b.y)    

          break;   

        for (i=0; i<4; i++)   

        {    

          x = d.x-1+dir[i][0];    

          y = d.y-1+dir[i][1];   

           if ((x<0) || (y<0) || (x>=m) || (y>=n))     

            continue;    

          if (map[x][y]==0 && visited[x][y]==0)    

          {     

            c.x = x+1;     

            c.y = y+1;     

            s.push(c);     

            visited[x][y] = 1;     

            break;    

          }

        }   

        if (i == 4)   

        {

          d = s.top();    

          map[d.x-1][d.y-1] = 1;    

          s.pop();   

        }  

      } 

       if (s.empty())  

      {   

        cout<<"没有找到路径"<<endl;  

      }  

      else  

      {   

         while (!s.empty())   

        {    

          Q.push(s.top());    

          s.pop();   

        }   

        c = Q.top();   

        cout<<"("<<c.x<<","<<c.y<<")";  

         Q.pop();   

        while (!Q.empty())   

        {    

          c = Q.top();    

          Q.pop();    

          cout<<"->("<<c.x<<","<<c.y<<")";  

         }   

        cout<<endl;  

      }

      return 0;

    }

  • 相关阅读:
    Qt 跟踪鼠标事件:setMouseTracking(true)
    Qt setMouseTracking使用
    Qt QGraphicsItem 鼠标点击事件编程方法
    Qt QGraphicsItem信号连接有关问题
    Qt 自定义QGraphicsItem
    Qt 视图框架QGraphicsItem
    Qt QGraphicsItem要点 积累
    Qt Q_UNUSED() 方法的使用
    Qt 绘图之QGraphicsScene QGraphicsView QGraphicsItem详解
    Qt 使用QGraphicsItem绘制复杂的图形
  • 原文地址:https://www.cnblogs.com/yazhou/p/3485083.html
Copyright © 2011-2022 走看看