您的位置:首页 > 其它

寻找迷宫出路

2014-04-13 18:58 351 查看
题目:

用一个10*10的矩阵代表迷宫,1为障碍物,0为通路,角色只能朝上下左右四个方向移动。

矩阵最外围一圈为1,代表围墙。入口坐标默认为(1,1)。

输入:

第一行有两个数,代表出口的横坐标和纵坐标。

第二行开始输入代表迷宫的矩阵。

输出:

如果存在离开迷宫的路径,则离开迷宫的路径,否则输出“NoPath”。

示例:



代码:

#include<iostream>
#include<stack>

using namespace std;

struct node
{
int row;
int col;
int dir;
};

int maze[10][10];
int mark[10][10];
bool found=false;
int zy[4]={-1,+1,0,0};
int zx[4]={0,0,-1,+1};
stack<node> stk;
int EXIT_row,EXIT_col;

void init()
{
for (int i=0;i<10;i++)
for (int j=0;j<10;j++)
mark[i][j]=0;
}

void input()
{
cin>>EXIT_row>>EXIT_col;
for (int i=0;i<10;i++)
for (int j=0;j<10;j++)
cin>>maze[i][j];
}

void find()
{
found=false;
while (!stk.empty())
{
stk.pop();
}
mark[1][1]=1;
node start;
start.row=1;
start.col=1;
start.dir=0;
stk.push(start);
while(!stk.empty()&&!found)
{
node position=stk.top();
int row=position.row;
int col=position.col;
int dir=position.dir;
while(dir<4&&!found)
{
int next_row=row+zy[dir];
int next_col=col+zx[dir];
if (next_row==EXIT_row && next_col==EXIT_col)
{
node exit;
exit.row=EXIT_row;
exit.col=EXIT_col;
exit.dir=0;
stk.push(exit);

found=true;
}
else if(maze[next_row][next_col]==0&&mark[next_row][next_col]==0)
{
mark[next_row][next_col]=1;
node next;
next.row=next_row;
next.col=next_col;
next.dir=0;

node top;
top=stk.top();
stk.pop();
top.dir=dir+1;
stk.push(top);

stk.push(next);
row=next_row;
col=next_col;
dir=0;
}else
{
dir++;
}
}
if(!found)
{
node top=stk.top();
row=top.row;
col=top.col;
mark[row][col]=0;
stk.pop();
}
}
}

void print()
{
if (!found)
{
cout<<"NoPath"<<endl;
}
else
{
while (!stk.empty())
{
node top=stk.top();
cout<<"("<<top.row<<","<<top.col<<")"<<endl;
stk.pop();
}
}
}

int main(){
init();
input();
find();
print();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: