Leetcode 3028. Ant on the Boundary
You are given a 2D grid of size m x n
where each cell represents a piece of land (denoted by ‘L’) or sea (denoted by an empty string “”). An ant starts at the top-left cell (0, 0) and can move in any of the four cardinal directions (left, right, up, down). The ant can only move to an adjacent piece of land (‘L’). Determine whether the ant can reach any piece of land on the boundary of the grid (the first row, last row, first column, or last column). Return true
if the ant can reach a boundary piece of land, otherwise return false
.
true
.false
.public class AntOnBoundary {
private int[][] directions = // use example from above
public boolean canReachBoundary(char[][] grid) {
int m = grid.length;
int n = grid[0].length;
boolean[][] visited = new boolean[m][n];
return dfs(grid, visited, 0, 0, m, n);
}
private boolean dfs(char[][] grid, boolean[][] visited, int x, int y, int m, int n) {
if (x < 0 || x >= m || y < 0 || y >= n || visited[x][y] || grid[x][y] != 'L') {
return false;
}
// If we are at a boundary and it's a land cell
if ((x == 0 || y == 0 || x == m - 1 || y == n - 1) && grid[x][y] == 'L') {
return true;
}
visited[x][y] = true;
for (int[] direction : directions) {
int newX = x + direction[0];
int newY = y + direction[1];
if (dfs(grid, visited, newX, newY, m, n)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
AntOnBoundary sol = new AntOnBoundary();
char[][] grid1 = {
{'L', 'L', 'L'},
{'L', '', 'L'},
{'L', 'L', 'L'}
};
System.out.println(sol.canReachBoundary(grid1)); // true
char[][] grid2 = {
{'L', 'L', 'L'},
{'', '', ''},
{'L', 'L', 'L'}
};
System.out.println(sol.canReachBoundary(grid2)); // true
char[][] grid3 = {
{'L', '', 'L'},
{'', 'L', ''},
{'L', '', 'L'}
};
System.out.println(sol.canReachBoundary(grid3)); // true
char[][] grid4 = {
{'L', '', ''},
{'', 'L', ''},
{'', '', 'L'}
};
System.out.println(sol.canReachBoundary(grid4)); // false
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?