迷宫问题

来源:互联网 发布:欧弟加入德云社 知乎 编辑:程序博客网 时间:2024/06/14 13:36



#include<iostream>

#include<cstdlib>
#include<cassert>
#include<stack>
const int N=10;
using namespace std;
struct Pos
{
int _row;
int _col;
Pos(int row=0,int col=0)
:_row(row)
,_col(col)
{}
};
void InitMaze(int* a)
{
FILE *fout=fopen("MazeMap.txt","r");
assert(fout);
for(int i=0;i<N;i++)
{
for(int j=0;j<N;)
{
char c=fgetc(fout);
if(c=='0'||c=='1')
{
a[i*N+j]=c-'0';
j++;
}
else
continue;
}
}
fclose(fout);
}
void PrintMaze(int a[][N])
{
   for(int i=0;i<N;i++)
   {
  for(int j=0;j<N;j++)
  {
  cout<<a[i][j]<<' ';
  
  }
      cout<<endl;
   }
   cout<<endl;
}
bool CheckIsAccess(int a[][N],Pos pos)


{
assert(a);
if((pos._row>=0)&&(pos._row<=N)&&(pos._col>=0)&&(pos._col<=N)&&a[pos._row][pos._col]==0)
{
return true;
}
else
{
return false;
}


 }
bool GetPash(int maze[][N],stack<Pos>& s,Pos entry)
{
s.push (entry);
maze[entry._row][entry._col]=2;
Pos tmp=entry;
Pos next=tmp;

while(!s.empty())
{

Pos cur=s.top();
   Pos tmp=cur;
         tmp._row -= 1;//上
if (CheckIsAccess(maze,tmp))
{
s.push(tmp);
maze[tmp._row][tmp._col] = 2;

continue;
}
tmp=cur;
tmp._row += 1;  //下
if (CheckIsAccess(maze,tmp))
{
s.push(tmp);
maze[tmp._row][tmp._col] = 2;
next=tmp;
continue;
}
tmp=cur;
tmp._col -= 1;   //左
if (CheckIsAccess(maze,tmp))
{
s.push(tmp);
maze[tmp._row][tmp._col] = 2;
next=tmp;
continue;
}


tmp=cur;
tmp._col += 1;    //右
if (CheckIsAccess(maze,tmp))
{
s.push(tmp);
maze[tmp._row][tmp._col] = 2;
next=tmp;
continue;
}
s.pop();
}
if (s.empty())         
return true;
return false;


}
void test()
{
int maze[N][N]={0};
int ret=0;
InitMaze((int*)maze);
PrintMaze(maze);
stack<Pos> path;
ret=GetPash(maze,path,Pos(2,0));
if(ret==1)
cout<<"有"<<endl;


    PrintMaze(maze);
}
int main()
{
test();
system("pause");
return 0;
}
0 0
原创粉丝点击