# 给定起始坐标和结束坐标，更改矩阵中两点之间路径上的值

##### 问题描述投票：0回答：1

#include <stdio.h>
#include <stdbool.h>

#define M 4
#define N 5
void dfs(int adj[][N], int i, int j, bool visited[][N])
{
if (i < 0 || i >= M || 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;
}
}

// Mark the start and end positions as part of the '0' trail

dfs(adj, sx, sy, visited);

return visited[dx][dy];
}

int main()
{
// 2D matrix with 1's as blocked and 0's as path.
int matrix[M][N] = {
{0, 0, 1, 0, 1},
{1, 2, 5, 0, 0},
{0, 0, 2, 0, 1},
{0, 5, 0, 0, 0}};

// Find path
int sx = 1, sy = 2, dx = 3, dy = 1;
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;
}

arrays c matrix path
##### 1个回答
0

visited

void dfs(int adj[][N], int i, int j, bool visited[][N], int poison)
{
if (i < 0 || i >= M || j < 0 || j >= N || adj[i][j] != 0 || visited[i][j])
{
return;
}
visited[i][j] = true;

dfs(adj, i - 1, j, visited, poison); // Move left
dfs(adj, i + 1, j, visited, poison); // Move Right
dfs(adj, i, j - 1, visited, poison); // Move top
dfs(adj, i, j + 1, visited, poison); // 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;
}
}

int poison = adj[sx][sy];

// Mark the start and end positions as part of the '0' trail