Example 1 — Solve a 4 by 4 maze
# is a wall and * marks the path from the top-left to the bottom-right.
#include <stdio.h>
#define N 4
static const int maze[N][N] = {
{0, 0, 0, 1},
{1, 0, 1, 1},
{0, 0, 0, 0},
{0, 1, 1, 0}
};
static int path[N][N], seen[N][N], backtracks;
static int solve(int r, int c) {
if (r < 0 || r >= N || c < 0 || c >= N || maze[r][c] || seen[r][c]) return 0;
seen[r][c] = 1;
path[r][c] = 1;
if (r == N - 1 && c == N - 1) return 1;
static const int dr[] = {0, 1, 0, -1};
static const int dc[] = {1, 0, -1, 0};
for (int d = 0; d < 4; d++)
if (solve(r + dr[d], c + dc[d])) return 1;
path[r][c] = 0;
backtracks++;
return 0;
}
int main(void) {
if (solve(0, 0)) {
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++)
printf("%c%s", maze[r][c] ? '#' : (path[r][c] ? '*' : '.'), c + 1 < N ? " " : "");
printf("\n");
}
}
printf("dead ends backtracked: %d\n", backtracks);
return 0;
} How It Works
- From the start the search goes right twice and reaches the dead end at row 0, column 2.
- That cell is unmarked and the search backs up to column 1, then goes down.
- It continues down and right to the goal; the dead-end cell is shown as
.because it is no longer on the path.
