1. 程式人生 > >NYOJ58 最少步數 【深搜】+【廣搜】

NYOJ58 最少步數 【深搜】+【廣搜】

最少步數

時間限制: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

廣搜:

#include <stdio.h>
#include <string.h>
#include <queue>
using std::queue;

bool 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
 }, vis[9][9]; 
 int ax, ay, bx, by;
 int mov[][2] = {0, 1, 0, -1, -1, 0, 1, 0};
 struct Node{
	int x, y, steps;
 };
 
 queue<Node> Q;
 
 void BFS(){
	Node temp, now;
	while(!Q.empty()){
		now = Q.front();
		Q.pop();
		if(now.x == bx && now.y == by){
			printf("%d\n", now.steps);
			return;
		}
		++now.steps;
		for(int i = 0; i < 4; ++i){
			temp = now;
			temp.x += mov[i][0];
			temp.y += mov[i][1];
			if(!vis[temp.x][temp.y] && !map[temp.x][temp.y]){
				vis[temp.x][temp.y] = 1;
				Q.push(temp);
			}
		}
	}
 }
 
 int main(){
	int n;
	scanf("%d", &n);
	while(n--){
		memset(vis, 0, sizeof(vis));
		scanf("%d%d%d%d", &ax, &ay, &bx, &by);
		Node temp; temp.x = ax;
		temp.y = ay; temp.steps = 0;
		while(!Q.empty()) Q.pop();
		Q.push(temp);
		BFS();
	}
	return 0;
 }
深搜:
 
#include <stdio.h>

bool sam[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 a, b, c, d, minlen, len;
 int f[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
 
 void DFS(int x, int y){
	if(len >= minlen) return;
	if(x == c && y == d){ minlen = len; return; }
	
	for(int i = 0; i < 4; ++i){
		if(sam[x+f[i][0]][y+f[i][1]] == 0){
			sam[x+f[i][0]][y+f[i][1]] = 1;
			++len;
			DFS(x+f[i][0], y+f[i][1]);
			--len;
			sam[x+f[i][0]][y+f[i][1]] = 0;
		}
	}	
	
 }
 
 int main(){
	int t;
	scanf("%d", &t);
	
	while(t--){
		scanf("%d%d%d%d", &a, &b, &c, &d);
		
		minlen = 100;
		len = 0;
		DFS(a, b);	

		printf("%d\n", minlen);
	}
	return 0;
 }