使用栈和队列求解迷宫问题(标准库)

来源:互联网 发布:java 利用poi生成ppt 编辑:程序博客网 时间:2024/04/29 05:39

迷宫储存在文件data.txt中:

* 表示墙壁

S 表示起点

O (注意不是数字0)代表通路

E 代表终点

---------------------------------------------------

6
11
***********
*SOOOOOOO0*
**O****O***
*OOO**OEOO*
****OO*****
*****OOO***

--------------------------------------------------

程序在DEV C++编译通过

--------------------------------------------------

 

#include <iostream>
#include <queue>
#include <stack>
#include <fstream>
#include <cstdlib>
using namespace std;

const int Size = 1000;

struct Node
{int x,y,count;};
      
char map[Size][Size];
int m,n,x1,y1,x2,y2,pi[Size*Size],min_count;
bool visit[Size][Size];
queue<Node> q;
      
void init()
{
    ifstream Data;
    Data.open("data.txt");
    int i,j;
    Node p;
    Data>>m>>n;
    for(i=0;i<m;i++)
    Data>>map[i];
    for(i=0;i<m;i++)
    for(j=0;j<n;j++)
    {pi[i*n+j]=-1;
     visit[i][j]=false;
     if(map[i][j]=='S')
     {x1=i;y1=j;}
     if(map[i][j]=='E')
     { x2=i;y2=j;}
    }
     p.x=x1;p.y=y1;p.count=0;q.push(p);
     visit[x1][y1]=true;min_count=0;
     Data.close();
}

void setNode(Node p,int x,int y)
{if(x<0||x>=m||y<0||y>=n)
return ;
if(visit[x][y]||map[x][y]=='*')
return ;
else
visit[x][y]=true;
pi[x*n+y]=p.x*n+p.y;
p.x=x;p.y=y;p.count++;
q.push(p);//压入
}

void work()
{Node p;
while (!q.empty())
{p=q.front();
q.pop();
   if(p.x==x2 && p.y==y2)
   {min_count=p.count;
   break;
   }

setNode(p,p.x-1,p.y);
setNode(p,p.x+1,p.y);
setNode(p,p.x,p.y-1);
setNode(p,p.x,p.y+1);
}
}

void print()
{if(min_count)
{cout<<"最小移动步数:"<<min_count<<endl;
stack<int> s;
s.push(x2*n+y2);
while( pi[ s.top( ) ] != -1 )
s.push( pi[ s.top( ) ] );
cout << "(" << x1+1 << ", " << y1+1 << ")";
s.pop( );
while ( !s.empty( ) )
{            cout << " -> (" << s.top( ) / n +1<< ", " << s.top( ) % n +1<< ")";
             s.pop( );   
}
cout << endl;
}
else
cout<<"没办法的" << endl;}

int main( )
{    init( );
     work( );
     print( );
     cin>>m;
     system("pause");
}