it is quite diff from baekjoon cuz here you shouldnt modify the given 2d list cuz it might be reused for each test case. While baekjoon resets the 2d list for each test case, Testdome doesnt so we have to make a copy of 2d list and modify it instead of the original 2d list like
// Create a copy of the mapMatrix to avoid modifying the original matrix
boolean[][] visited = new boolean[x][y];
for (int i = 0; i < x; i++) {
System.arraycopy(mapMatrix[i], 0, visited[i], 0, y);
}
in py, this is same as a deep copy where inner lists are also copied (not shallow copy via .copy())
# Create a copy of the map_matrix to avoid modifying the original matrix
visited = [row[:] for row in map_matrix]
public static boolean routeExists(int fromRow, int fromColumn, int toRow, int toColumn,
boolean[][] mapMatrix) {
int x = mapMatrix.length;
int y = mapMatrix[0].length;
// Create a copy of the mapMatrix to avoid modifying the original matrix
boolean[][] visited = new boolean[x][y];
for (int i = 0; i < x; i++) {
System.arraycopy(mapMatrix[i], 0, visited[i], 0, y);
}
return dfs(fromRow, fromColumn, toRow, toColumn, visited, x, y);
}
public static boolean dfs(int row, int col, int toRow, int toColumn,
boolean[][] visited, int x, int y) {
if (row == toRow && col == toColumn) {
return true;
}
int[][] moves = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int[] move : moves) {
int nextRow = move[0] + row;
int nextCol = move[1] + col;
if (0 <= nextRow && nextRow < x && 0 <= nextCol && nextCol < y) {
if (visited[nextRow][nextCol]) {
visited[nextRow][nextCol] = false;
if (dfs(nextRow, nextCol, toRow, toColumn, visited, x, y)) {
return true;
}
}
}
}
return false;
}