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;
 }        



你可能感兴趣的:(nyoj58)