Sponsored
Sponsored
This approach involves using a binary search to find the last day a path exists from top to bottom. For each midpoint in the binary search, simulate the grid's flooding and check path connectivity using Depth First Search (DFS). Start by initializing the grid as land then flood the cells according to the days up to midpoint. Using DFS, attempt to find a path from the top to the bottom row.
Time Complexity is O(n * m * log(n * m)) where n is the number of rows and m is the number of columns. Space Complexity is O(n * m) for the visited matrix.
1var latestDayToCross = function(row, col, cells) {
2 const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
3 let grid, r, c;
4
5 const isValid = (x, y) => {
6 return x >= 0 && x < r && y >= 0 && y < c && grid[x][y] === 0;
7 };
8
9 const dfs = (x, y) => {
10 if (x === r - 1) return true;
11 grid[x][y] = 1;
12 for (const [dx, dy] of directions) {
13 const nx = x + dx, ny = y + dy;
14 if (isValid(nx, ny) && dfs(nx, ny)) return true;
15 }
16 return false;
17 };
18
19 const canCross = (day) => {
20 grid = Array.from({ length: row }, () => Array(col).fill(0));
21 for (let i = 0; i <= day; i++) {
22 grid[cells[i][0] - 1][cells[i][1] - 1] = 1;
23 }
24 for (let i = 0; i < col; i++) {
25 if (grid[0][i] === 0 && dfs(0, i)) return true;
26 }
27 return false;
28 };
29
30 let left = 0, right = cells.length - 1, lastValidDay = 0;
31 while (left <= right) {
32 const mid = left + Math.floor((right - left) / 2);
33 if (canCross(mid)) {
34 lastValidDay = mid;
35 left = mid + 1;
36 } else {
37 right = mid - 1;
38 }
39 }
40 return lastValidDay + 1;
41};
This JavaScript formulation applies binary search integrated with DFS to determine if a path exists up to a certain day. By using grid simulation based on binary search midpoints, it finds the last feasible day for the top-to-bottom path.
This approach involves using a union-find data structure to efficiently check connectivity between the top and bottom rows during a binary search over the days. For each day in the binary search, the cells flooded up to that day are processed, and union operations are performed on adjacent land cells. We add virtual top and bottom nodes in the union-find structure to track connectivity between the top and bottom row cells.
Time Complexity is O(n * m * log(n * m)) due to union-find operations, and Space Complexity is O(n * m) for the union-find parent and rank tracking.
In this JavaScript strategy, union-find solutions leverage connectivity determinations for evaluating days up to the binary search midpoint. This approach ascertains maximal crossing day via virtual node integration.