E - 迷宫问题 (DFS)

定义一个二维数组:
int maze[5][5] = {

	0, 1, 0, 0, 0,

	0, 1, 0, 1, 0,

	0, 0, 0, 0, 0,

	0, 1, 1, 1, 0,

	0, 0, 0, 1, 0,

};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

求0,0到4,4的最短路径简单,但是要记录到4,4点的过程,就需要思考一下了,可以在每次的搜索开始就进行标记,找到时,就把值给传出去,防止改变值的大小。

代码如下:

# include <stdio.h>

int book[6][6], a[6][6], min;
int next[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};  //  四个方向 

struct qwe // 记录x,y的坐标。 
{
	int x[30];
	int y[30];
}q, q1;

void dfs(int x, int y, int step)
{
	q1.x[step] = x;  //  记录坐标 
	q1.y[step] = y;

	if (x == 4 && y == 4)
	{
		if (step < min)
		{		
			q = q1;  // 将记录的最短路径传入q, 防止回溯改变q1的值 
			min = step;
		}
		return;
	}
	int k, tx, ty;
	for (k = 0; k < 4; k ++)
	{
		tx = x + next[k][0];
		ty = y + next[k][1];
		if (tx < 0 || tx > 4 || ty < 0 ||ty > 4)
			continue;   //墙体跳过 
			
		if (a[tx][ty] == 0 && book[tx][ty] == 0)
		{
			book[tx][ty] = 1;
			dfs(tx, ty, step + 1);
			book[tx][ty] = 0;   // 取消标记 
		}
	}
	return;
}
int main(void)
{
	int i, j;
	for (i = 0; i < 5; i ++)
		for (j = 0; j < 5; j ++)
			scanf("%d", &a[i][j]);
	book[0][0] = 1;
	min = 99999999;
	dfs(0, 0, 0);
	for (i = 0; i <= min; i ++)
		printf("(%d, %d)\n", q.x[i], q.y[i]);
		
	return 0;
}

猜你喜欢

转载自blog.csdn.net/liu344439833/article/details/80224518