现在的位置: 首页 > 综合 > 正文

走出迷宫

2018年04月04日 ⁄ 综合 ⁄ 共 1710字 ⁄ 字号 评论关闭

    用矩阵建立图,s为迷宫的起点,t为迷宫的终点,输出走出迷宫路线的坐标

    步骤:

     1)建立栈

     2)判断下一步是否可达,可达则结束判断

     3)不可达则前进,按上下左右地前进。

/* 迷宫求解
6
#s####
#O####
#O####
#O####
#OOOOt
######
10
##########
#sO#OOO#O#
#OO#OOO#O#
#OOOO##OO#
#O###OOOO#
#OOO#OOOO#
#O#OOO#OO#
#O###O##O#
##OOOOOOt#
##########

 */
#include <iostream>
#include <stack>
using namespace std;
#define  MAX 1000
struct Node
{
	int x, y;
}tmp, s, t, order[MAX];
char Graph[MAX][MAX];

int IsFind(int x, int y)
{
     if (x==t.x && y==t.y)
		 return 1;
	 return 0;
}
int Judge(stack<struct Node> &sta) //判断是否到达t
{
	if (IsFind(tmp.x+1, tmp.y))
	{
		tmp.x = tmp.x + 1;
		sta.push(tmp);
		return 1;
	}
	else if (IsFind(tmp.x-1, tmp.y))
	{
		tmp.x = tmp.x - 1;
		sta.push(tmp);
		return 1;
	}
	else if (IsFind(tmp.x, tmp.y+1))
	{
		tmp.y = tmp.y + 1;
		sta.push(tmp);
	    return 1;
	}
	else if (IsFind(tmp.x, tmp.y-1))
	{
		tmp.y = tmp.y - 1;
		sta.push(tmp);
	    return 1;
	}
	return 0;
}
void Advance(stack<struct Node> &sta)
{
    if (Graph[tmp.x+1][tmp.y]=='O')
	{
		Graph[tmp.x][tmp.y] = '#';
		tmp.x = tmp.x + 1;
		sta.push(tmp);
	}
	else if (Graph[tmp.x-1][tmp.y]=='O')
	{
		Graph[tmp.x][tmp.y] = '#';
		tmp.x = tmp.x - 1;
		sta.push(tmp);
	}
	else if (Graph[tmp.x][tmp.y+1]=='O')
	{
		Graph[tmp.x][tmp.y] = '#';
		tmp.y = tmp.y + 1;
		sta.push(tmp);
	}
	else if (Graph[tmp.x][tmp.y-1]=='O')
	{
		Graph[tmp.x][tmp.y] = '#';
		tmp.y = tmp.y - 1;
		sta.push(tmp);
	}
	else
	{
		tmp = sta.top();
		Graph[tmp.x][tmp.y] = '#';
		sta.pop();
	}
}
int main()
{
	int num, i, j;
	while (cin>>num && num)
	{
        for (i=0; i<num; i++)
			for (j=0; j<num; j++)
			{
				cin>>Graph[i][j];
				if (Graph[i][j]=='s')
				{ s.x = i, s.y = j;}
				else if (Graph[i][j]=='t')
				{t.x = i, t.y = j;}
			}
		stack<struct Node> sta;
		sta.push(s);
		while (!sta.empty())
		{
			tmp = sta.top();
			if (Judge(sta))//下一步是否可达
				break;
			Advance(sta);//前进
		}
		if (sta.empty())
			cout<<"找不到出口"<<endl;
		else
		{
		     j = i = sta.size();
			while (!sta.empty())
			{
			   	order[i] = sta.top();
				sta.pop();
				i--;
			}
			for (i=1; i<=j; i++)
			{
				if (i==1)
					cout<<'('<<order[i].x<<','<<order[i].y<<')';
				else
                   	cout<<"->("<<order[i].x<<','<<order[i].y<<')';
			}
			cout<<endl;
		}
	
	}
	return 0;
}



抱歉!评论已关闭.