NYOJ-最少步数(dfs)

67 阅读2分钟

最少步数

 

描述:
这有一个迷宫,有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

#include<stdio.h>
#include<string.h>
int a,b,c,d,min;
int s[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 book[9][9];
void dfs(int x,int y,int step);
int main()
{
	int n,step;
	scanf("%d",&n);
	while(n--)
	{
		min=99999999;
		memset(book,0,sizeof(book));
		scanf("%d%d%d%d",&a,&b,&c,&d);
		book[a][b]=1;
		step=0;
		dfs(a,b,step);
		printf("%d\n",min);
	}	
	return 0;
}
void dfs(int x,int y,int step)
{
	int tx,ty,k;
	int next[4][2]={0,1,1,0,0,-1,-1,0};
	if(x==c&&y==d)
	{
		if(step<min)
			min=step;
		return;
	}
	for(k=0;k<4;k++)
	{
		tx=x+next[k][0];
		ty=y+next[k][1];
		if(tx<0||tx>8||ty<0||ty>8)
			continue;
		if(s[tx][ty]==0&&book[tx][ty]==0)
		{
			book[tx][ty]=1;
			dfs(tx,ty,step+1);
			book[tx][ty]=0;
		}
	}
	return;
}

 


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

 

程序代码: