写了个迷宫程序,给大神看下,运行中出现错误。
#include<iostream>
#include<fstream>
#include<string>
#include<stack>
using namespace std;
ifstream inFile("test.txt");
int num=0;
char Maze[10][10];
typedef struct
{
int x;
int y;
}PosType;
PosType block[100];
typedef struct
{
int ord;
PosType seat;
int di;
}SElemType;
bool Pass(PosType curpos)
{
if(Maze[curpos.x][curpos.y]=='0')
return false;
else
{
int j=0;
while(j<num)
{
if(curpos.x==block[j].x && curpos.y==block[j].y)
return false;
j++;
}
}
return true;
}
PosType NextPos(PosType curpos,int di)
{
if(di==1)
{
curpos.x=curpos.x+1;
return curpos;
}
if(di==2)
{
curpos.y=curpos.y+1;
return curpos;
}
if(di==3)
{
curpos.x=curpos.x-1;
return curpos;
}
else
{
curpos.y=curpos.y-1;
return curpos;
}
}
void FootPrint(PosType curpos)
{
Maze[curpos.x][curpos.y]='!';
}
void MarkPrint(PosType curpos)
{
block[num]=curpos;
num++;
}
bool MazePath(PosType start,PosType end)
{
stack<SElemType> S;
PosType curpos=start;
int curstep=1;
SElemType e;
do{
if(Pass(curpos))
{
FootPrint(curpos);
e.ord=curstep;
e.seat=curpos;
e.di=1;
S.push(e);
if(curpos.x==end.x && curpos.y==end.y)
return (true);
curpos=NextPos(curpos,1);
curstep++;
}
else
{
if(!S.empty())
S.pop();
while(e.di==4 && !S.empty())
{
MarkPrint(e.seat);
S.pop();
}
if(e.di<4)
{
e.di++;
S.push(e);
curpos=NextPos(e.seat,e.di);
}
}
}while(!S.empty());
}
int main()
{
string temp;
for(int a=0;a<=9;a++)
{
getline(inFile,temp);
for(int b=0;b<=9;b++)
{
Maze[a][b]=temp[b];
}
}
PosType start,end;
start.x=1;
start.y=1;
end.x=8;
end.y=8;
MazePath(start,end);
for(int i=0;i<=9;i++)
{
for(int j=0;j<=9;j++)
{
cout<<Maze[i][j];
}
cout<<endl;
}
int k;
cin>>k;
return 0;
}
-----------------------------------------------------------
下面是test.txt
0000000000
0 0 0 0
0 0 0 0
0 00 0
0 000 0
0 0 0
0 0 0 0
0 000 00 0
00 0
0000000000
[解决办法]
看了一下程序, 貌似进入了死循环...
你使用'!'去标志所走过的路, curpos=NextPos(curpos,1); /以curpos为基点,深度遍历; 但是调试走到Maze[7][0] == ' '; 当走到Maze[8][0]时 Maze[8][0] == '0' 时,pass函数返回false, 在以Maze[7][0]做广度遍历,
返回Maze[6][0], 但是此时的Maze[6][0] == '!'; 进入pass函数里面依然返回true;
所以在函数bool pass(PosType curpos)里面应该加一种判断:
if( Max[curpos.x][curpos.y] )
return false;
写了个迷宫程序,给大神看下,运行中出现异常
写了个迷宫程序,给大神看下,运行中出现错误。#includeiostream#includefstream#includestring#includ
