*******深搜和广搜结合********

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LMengi000/article/details/81807227

目录

 

POJ 3984 迷宫问题


POJ 3984 迷宫问题

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<stdlib.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
struct pos
{
	int r,c;
	int father;
	pos(int rr=0,int cc=0,int ff=0):r(rr),c(cc),father(ff){ } //不断重新给 r,c,father赋值 
};
int maze[8][8];
pos que[100]; 
int head,tail;
pos dir[4]={pos(-1,0),pos(1,0),pos(0,-1),pos(0,1)}; //四个方向 
int main()
{
      memset(maze,0xff,sizeof(maze));
      for(int i=1;i<=5;++i)
      {
      	for(int j=1;j<=5;++j)
      	{
          cin>>maze[i][j];
	    }
	  }
	  head=0;
	  tail=1;
	  que[0]=pos(1,1,-1);
	  while(head!=tail)
	  {
	  	pos ps=que[head];
	  	if(ps.r==5 && ps.c==5)
	  	{
	  	  vector<pos>vt;
		  while(true)	
		  {
		  	vt.push_back(pos(ps.r,ps.c,0));
		  	if(ps.father==-1)
		  	  break;
		  	ps=que[ps.father];
		  };
		  for(int i=vt.size()-1;i>=0;i--)
		    cout<<"("<<vt[i].r-1<<", "<<vt[i].c-1<<")"<<endl;
		    return 0;
		}
		else
		{
			int r=ps.r,c=ps.c;
			for(int i=0;i<4;++i)
				if(!maze[r+dir[i].r][c+dir[i].c])
				{
					que[tail++]=pos(r+dir[i].r,c+dir[i].c,head);
					maze[r+dir[i].r][c+dir[i].c]=1;
				}
				++head;
		}
	  }
	  return 0;
}

自己之前代码:

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
struct Node
{
	int x;
	int y;
}v[20][20];
int vis[20][20];
int dir[4][2]={0,1,1,0,0,-1,-1,0};
int g[20][20];
queue<Node>Q;
void dfs(int x,int y)
{
	if(x==0 && y==0)
	{
		return ;
	}
	dfs(v[x][y].x,v[x][y].y);
	printf("(%d, %d)\n",v[x][y].x,v[x][y].y);
}
void bfs(int a,int b)
{
	Node last,now;
	last.x=a;
	last.y=b;
	Q.push(last);
	while(!Q.empty())
	{
		last=Q.front();
		Q.pop();
		if(last.x==4 && last.y==4)
		{
			dfs(last.x,last.y);
			printf("(%d, %d)\n",last.x,last.y);
			return ;
		}
		for(int i=0;i<4;i++)
		{
			now.x=last.x+dir[i][0];
			now.y=last.y+dir[i][1];
			if(now.x>=0 && now.x<=4 && now.y>=0 && now.y<=4 && g[now.x][now.y]!=1 &&!vis[now.x][now.y])
			{
				v[now.x][now.y].x=last.x;
				v[now.x][now.y].y=last.y;
				vis[now.x][now.y]=1;
				Q.push(now);
			}
		}
	}
}
int main()
{
	for(int i=0;i<5;i++)
	{
		for(int j=0;j<5;j++)
	    {
	        scanf("%d",&g[i][j]);
		}
	}
	bfs(0,0);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/LMengi000/article/details/81807227