SDUT 1157-小鼠迷宮問題(BFS&DFS)

小鼠迷宮問題

Time Limit: 1500ms   Memory limit: 65536K  有疑問?點這裏^_^

題目描寫敘述

小鼠a與小鼠b身處一個m×n的迷宮中。如圖所看到的。每一個方格表示迷宮中的一個房間。這m×n個房間中有一些房間是封閉的,不一樣意不論什麼人進入。在迷宮中不論什麼位置都可沿上,下。左,右4個方向進入未封閉的房間。

小鼠a位於迷宮的(p。q)方格中,它必須找出一條通向小鼠b所在的(r,s)方格的路。請幫助小鼠a找出所有通向小鼠b的最短道路。php

 



 請編程對於給定的小鼠的迷宮,計算小鼠a通向小鼠b的所有最短道路。html

輸入

本題有多組輸入數據,你必須處理到EOF爲止。
每組數據的第一行有3個正整數n,m。k,分別表示迷宮的行數,列數和封閉的房間數。
接下來的k行中。每行2個正整數。表示被封閉的房間所在的行號和列號。
最後的2行。每行也有2個正整數,分別表示小鼠a所處的方格(p,q)和小鼠b所處的方格(r,s)。

輸出

對於每組數據,將計算出的小鼠a通向小鼠b的最短路長度和有多少條不一樣的最短路輸出。
每組數據輸出兩行,第一行是最短路長度;第2行是不一樣的最短路數。
每組輸出之間沒有空行。


假設小鼠a沒法通向小鼠b則輸出「No Solution!」。java

演示樣例輸入

8 8 3
3 3
4 5
6 6
2 1
7 7

演示樣例輸出

11
96
BFS搜到最短路徑。

。而後BFS怒搜路徑數node

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <cstdlib>
#include <set>
#include <map>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <cmath>
#define LL long long
using namespace std;
const int INF = 0x3f3f3f3f;
struct node
{
	int x,y,step;
};
int sb,ans,n,m,sx,sy,ex,ey,dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
bool ma[110][110],vis[110][110];
int bfs()
{
	memset(vis,0,sizeof(vis));
	queue <node> Q;
	node now,next;
	now.x=sx;now.y=sy;now.step=0;
	vis[sx][sy]=1;
	Q.push(now);
	while(!Q.empty())
	{
		now=Q.front();Q.pop();
		if(now.x==ex&&now.y==ey)
			return now.step;
		for(int i=0;i<4;i++)
		{
			next.x=now.x+dir[i][0];
			next.y=now.y+dir[i][1];
			if(next.x>=1&&next.x<=n&&next.y>=1&&next.y<=m&&!vis[next.x][next.y]&&ma[next.x][next.y])
			{
				vis[next.x][next.y]=1;
				next.step=now.step+1;
				Q.push(next);
			}
		}
	}
	return -1;
}
void dfs(int x,int y,int step)
{
	if(step>sb) return ;
	if(x==ex&&y==ey&&step==sb)
	{
		++ans;
		return ;
	}
	for(int i=0;i<4;i++)
	{
		int tx=x+dir[i][0];
		int ty=y+dir[i][1];
		if(tx>=1&&tx<=n&&ty>=1&&ty<=m&&!vis[tx][ty]&&ma[tx][ty])
		{
			vis[tx][ty]=1;
			dfs(tx,ty,step+1);
			vis[tx][ty]=0;
		}
	}
}
int main()
{
	int k,u,v;
	while(~scanf("%d%d%d",&n,&m,&k))
	{
		memset(ma,1,sizeof(ma));
		while(k--)
		{
			scanf("%d%d",&u,&v);
			ma[u][v]=0;
		}
		scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
		sb=bfs();
		if(sb==-1)
		{
			puts("No Solution!");
			continue;
		}
		printf("%d\n",sb);
		memset(vis,0,sizeof(vis));
		ans=0;vis[sx][sy]=1;
		dfs(sx,sy,0);
		printf("%d\n",ans);
	}
	return 0;
}
相關文章
相關標籤/搜索