-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathValidator.java
More file actions
56 lines (48 loc) · 1.51 KB
/
Copy pathPathValidator.java
File metadata and controls
56 lines (48 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class PathValidator {
private char[][] grid;
private boolean[][] visited;
private int rows, cols;
private int startRow, startCol;
public PathValidator(char[][] grid) {
this.grid = grid;
this.rows = grid.length;
this.cols = grid[0].length;
this.visited = new boolean[rows][cols];
findStart();
}
private void findStart() {
// Locate the first start cell and use it as the DFS entry point.
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == 'S') {
startRow = i;
startCol = j;
return;
}
}
}
}
public boolean pathExists() {
return dfs(startRow, startCol);
}
private boolean dfs(int r, int c) {
// Stop recursion when coordinates are outside the grid.
if (r < 0 || c < 0 || r >= rows || c >= cols) {
return false;
}
// Walls and already visited cells cannot be part of a valid path.
if (grid[r][c] == '1' || visited[r][c]) {
return false;
}
// Reaching the end cell means a valid path exists.
if (grid[r][c] == 'E') {
return true;
}
visited[r][c] = true;
// Explore all four directions (down, up, right, left).
return dfs(r + 1, c) ||
dfs(r - 1, c) ||
dfs(r, c + 1) ||
dfs(r, c - 1);
}
}