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

POJ 3984 顶嵌杯决赛 B题

2017年11月22日 ⁄ 综合 ⁄ 共 1243字 ⁄ 字号 评论关闭
迷宫问题
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 990   Accepted: 498

Description

定义一个二维数组:
int maze[5][5] = {

	0, 1, 0, 0, 0,

	0, 1, 0, 1, 0,

	0, 0, 0, 0, 0,

	0, 1, 1, 1, 0,

	0, 0, 0, 1, 0,

};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

Source

    #include<stdio.h>
    #include<string.h>
    #include<algorithm>
    #include<queue>

    using namespace std;

    struct node
    {
    	int x;
    	int y;
    };

    node path[30][30];
    int map[5][5];
    int used[5][5];
    int dx[4]={1,-1,0,0};
    int dy[4]={0,0,1,-1};

    bool judge(int x,int y)
    {
    	if(x>=0&&x<5&&y>=0&&y<5)
    		return true;
    	else
    		return false;
    }

    void bfs(int x,int y)
    {
    	int nx,ny,i;
    	node k1,k2;
    	k1.x=x;
    	k1.y=y;
    	queue<node>q;
    	q.push(k1);
    	while(!q.empty())
    	{
    		k2=q.front();
    		q.pop();
    		if(k2.x==4&&k2.y==4)
    		{
    			return;
    		}
    		for(i=0;i<4;i++)
    		{
    			nx=k2.x+dx[i];
    			ny=k2.y+dy[i];
    			if(judge(nx,ny)&&!used[nx][ny])
    			{
    				used[nx][ny]=1;
    				k1.x=nx;
    				k1.y=ny;
    				path[nx][ny]=k2;
    				q.push(k1);
    			}
    		}
    	}
    }

    int main()
    {
    	int i,j;
    	for(i=0;i<5;i++)
    		for(j=0;j<5;j++)
    		{
    			scanf("%d",&map[i][j]);
    			if(map[i][j])
    			{
    				used[i][j]=map[i][j];
    			}
    		}
    	node tmp,ans[30];
    	int cnt=0;
    	bfs(0,0);
    	tmp.x=4;
    	tmp.y=4;
    	while(tmp.x!=0||tmp.y!=0)
    	{
    		tmp=path[tmp.x][tmp.y];
    		ans[cnt++]=tmp;
    	}
    	for(i=cnt-1;i>=0;i--)
    		printf("(%d, %d)/n",ans[i].x,ans[i].y);
    	printf("(4, 4)/n");
    	return 0;
    }

 

抱歉!评论已关闭.