1. 程式人生 > >DFS && BFS 最少步數(nyoj 58)

DFS && BFS 最少步數(nyoj 58)

最少步數

最少步數

時間限制:3000 ms  |  記憶體限制:65535 KB 難度:4
描述

這有一個迷宮,有0~8行和0~8列:

 1,1,1,1,1,1,1,1,1
 1,0,0,1,0,0,1,0,1
 1,0,0,1,1,0,0,0,1
 1,0,1,0,1,1,0,1,1
 1,0,0,0,0,1,0,0,1
 1,1,0,1,0,1,0,0,1
 1,1,0,1,0,1,0,0,1
 1,1,0,1,0,0,0,0,1
 1,1,1,1,1,1,1,1,1

0表示道路,1表示牆。

現在輸入一個道路的座標作為起點,再如輸入一個道路的座標作為終點,問最少走幾步才能從起點到達終點?

(注:一步是指從一座標點走到其上下左右相鄰座標點,如:從(3,1)到(4,1)。)

輸入
第一行輸入一個整數n(0<n<=100),表示有n組測試資料;
隨後n行,每行有四個整數a,b,c,d(0<=a,b,c,d<=8)分別表示起點的行、列,終點的行、列。
輸出
輸出最少走幾步。
樣例輸入
2
3 1  5 7
3 1  6 7
樣例輸出
12
11

DFS:

<span style="font-size:18px;"> 
#include<cstdio>
using namespace std;
int map[9][9]={1,1,1,1,1,1,1,1,1,
 1,0,0,1,0,0,1,0,1,
 1,0,0,1,1,0,0,0,1,
 1,0,1,0,1,1,0,1,1,
 1,0,0,0,0,1,0,0,1,
 1,1,0,1,0,1,0,0,1,
 1,1,0,1,0,1,0,0,1,
 1,1,0,1,0,0,0,0,1,
 1,1,1,1,1,1,1,1,1};
int sum;
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
int x,y;

void dfs(int a,int b,int count){
		if (a==x&&b==y){
		if (count<sum)
		sum=count;

		}
		else{
			for (int i=0;i<4;i++){
			int xx=a+dx[i];
		int yy=b+dy[i];
		if (map[xx][yy]==0&&count+1<sum){
			map[xx][yy]=1;
			dfs(xx,yy,count+1);
			map[xx][yy]=0;
			}
		}
	
			}
		
	}

int main(){
	int n;
	int a,b;
	scanf ("%d",&n);
	while (n--){
		scanf ("%d %d %d %d",&a,&b,&x,&y);
		int count=0;
		map[a][b]=1;
		sum=10000;
		dfs(a,b,count);
		map[a][b]=0;
		printf ("%d\n",sum);
	}
	return 0;
	
	
}        </span>

BFS:

<span style="font-size:18px;">#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;

int map[9][9]={
1,1,1,1,1,1,1,1,1,
 1,0,0,1,0,0,1,0,1,
 1,0,0,1,1,0,0,0,1,
 1,0,1,0,1,1,0,1,1,
 1,0,0,0,0,1,0,0,1,
 1,1,0,1,0,1,0,0,1,
 1,1,0,1,0,1,0,0,1,
 1,1,0,1,0,0,0,0,1,
 1,1,1,1,1,1,1,1,1,
};

struct node{
	int x,y,step;
}s,end,now;
int vis[9][9];
int n,a,b,c,d;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};

int bfs(){
	s.x = a;s.y=b;s.step=0;
	vis[a][b]=true;
	queue<node>q;
	q.push(s);
	while (!q.empty()){
		now = q.front();
		q.pop();
		if (now.x==c && now.y==d){
		return now.step;
	}
	for (int i=0;i<4;i++){
		end.x=dx[i]+now.x;
		end.y=dy[i]+now.y;
		end.step=now.step;
		if (map[end.x][end.y]==0&&!vis[end.x][end.y]){//少寫!vis[][],超記憶體 
			end.step++;
			vis[end.x][end.y]=true;
			q.push(end);
		}
	}	
	}
	
}
int main(){

	scanf ("%d",&n);
	while (n--){
		scanf ("%d %d %d %d",&a,&b,&c,&d);
		memset(vis,false,sizeof(vis));
		int ans=bfs();
		printf ("%d\n",ans);
	}
	return 0;
	
} </span>
區別:BFS搜尋到的就是最優解,DFS需要判斷更新出最優解