最少步數

/*描述
這有一個迷宮,有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>
int a,b,c,d,count,m;
int maze[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},
}; 
void fun(int a,int b,int s)
{
	if(a==c&&b==d)
	{
		m=s>m?m:s;
	return ;
	}
	if(maze[a][b]==1||a<0||b<0||a>9||b>9)
	return ;
	s++;
	maze[a][b]=1;
	fun(a,b+1,s);
	fun(a,b-1,s);
	fun(a+1,b,s);
	fun(a-1,b,s);
	
	maze[a][b]=0;
}
int main()
{
	int n;
	scanf("%d",&n);
	while(n--)
	{
		m=0x3f3f3f;
		scanf("%d%d%d%d",&a,&b,&c,&d);
		fun(a,b,0);
		printf("%d\n",m);
		
	}
	return 0;
}

發佈了68 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章