E - Maze Problem (DFS)

Define a two-dimensional array:
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,

};

It represents a maze, in which 1 represents a wall, and 0 represents a path that can be walked. You can only walk horizontally or vertically, and you cannot walk diagonally. It requires programming to find the shortest route from the upper left corner to the lower right corner.
Input
A 5 × 5 two-dimensional array representing a maze. The data is guaranteed to have a unique solution.
Output
The shortest path from the upper left corner to the lower right corner, in the format shown in the example.
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)

It is simple to find the shortest path from 0, 0 to 4, 4, but to record the process of points 4 and 4, you need to think about it. You can mark the beginning of each search, and when you find it, send the value out. , to prevent changing the size of the value.

code show as below:

# include <stdio.h>

int book[6][6], a[6][6], min;
int next[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; // four directions

struct qwe // Record x, y coordinates.
{
	int x[30];
	int y[30];
}q, q1;

void dfs(int x, int y, int step)
{
	q1.x[step] = x; // record coordinates
	q1.y[step] = y;

	if (x == 4 && y == 4)
	{
		if (step < min)
		{		
			q = q1; // Pass the recorded shortest path into q to prevent backtracking from changing the value of 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; //Wall skip
			
		if (a[tx][ty] == 0 && book[tx][ty] == 0)
		{
			book[tx][ty] = 1;
			dfs(tx, ty, step + 1);
			book[tx][ty] = 0; // unmark
		}
	}
	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;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325760009&siteId=291194637