In the code below, I tried to write a program that checks whether there is a path consisting of 0s from the starting coordinate (sx,sy) to (dx,dy). For instances from (0,0) to (3,3) there seems to be a path of 0s and the output should be true. But I am not getting the correct result. It doesn't work the way I want. Can you help me to find my mistake?
#include <stdio.h>
#include <stdbool.h>
#define N 5
void dfs(int adj[][N], int i, int j, bool visited[][N]);
bool hasPathDfs(int adj[][N], int sx, int sy, int dx, int dy);
int main()
{
int matrix[N][N] = {
{1, 0, 0, 0, 0},
{2, 3, 0, 3, 1},
{0, 4, 0, 0, 0},
{0, 0, 0, 2, 4},
{5, 0, 0, 2, 5}};
// Find path
int sx = 0, sy = 0, dx = 3, dy = 3;
printf("Find path from (%d,%d) to (%d,%d):\n", sx, sy, dx, dy);
printf("DFS: %s\n", hasPathDfs(matrix, sx, sy, dx, dy) ? "true" : "false");
return 0;
}
// Function Declarations
void dfs(int adj[][N], int i, int j, bool visited[][N])
{
if (i < 0 || i >= N || j < 0 || j >= N || adj[i][j] != 0 || visited[i][j])
{
return;
}
visited[i][j] = true;
dfs(adj, i - 1, j, visited); // Move left
dfs(adj, i + 1, j, visited); // Move Right
dfs(adj, i, j - 1, visited); // Move top
dfs(adj, i, j + 1, visited); // Move bottom
}
bool hasPathDfs(int adj[][N], int sx, int sy, int dx, int dy)
{
bool visited[N][N];
int i,j;
for ( i = 0; i < N; i++)
{
for ( j = 0; j < N; j++)
{
visited[i][j] = false;
}
}
dfs(adj, sx, sy, visited);
if (!visited[dx][dy])
{
return false;
}
return true;
}