最小步數nyoj--92

最少步數
時間限制: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>

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

typedef struct pos
{
	int x, y;
	int count;
}Pos;

typedef struct que
{
	Pos pos[100];
	int rear, front;
}Qu;

int a, b, c, d;
int dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
void bfs(Qu *que);

int main()
{
	int n;
	Qu que;

	scanf("%d", &n);
	getchar();

	while(n--)
	{
		que.rear = -1;
		que.front = 0;
		scanf("%d %d  %d %d", &a, &b, &c, &d);
		getchar();
		
		if(a == c && b == d)
			printf("0\n");
		else
			bfs(&que);
	}

	return 0;
}

void bfs(Qu *que)
{
	int i, x1, y1, x, y, flag = 0, mark[10][10] = {0};
	
	que->rear++;
	que->pos[que->rear].x = a;
	que->pos[que->rear].y = b;
	que->pos[que->rear].count =0;//開始時層數爲0

	for(;;)
	{
		x = que->pos[que->front].x;
		y = que->pos[que->front].y;
		flag = que->pos[que->front].count; //記錄層數
		que->pos[que->front].x = -1;
		que->pos[que->front].y = -1;
		que->front++;

		for(i = 0; i < 4; i++)
		{
			x1 = x + dir[i][0];
			y1 = y + dir[i][1];
			
			if(x1 < 0 || y1 < 0 || map[x1][y1] == 1 || x1 >=9 || y1 >= 9 || mark[x1][y1] == 1)
				continue;
			mark[x1][y1] = 1;//標記已經走過的點
			que->rear++;
			que->pos[que->rear].x = x1;
			que->pos[que->rear].y = y1;
			que->pos[que->rear].count =flag + 1;
			if(x1 == c && y1 == d)
			{
				printf("%d\n", flag + 1);
				return ;
			}
		}
	}
}


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