|
| 1 | +/** |
| 2 | + * Breath First Search implementation |
| 3 | + * @param matrix |
| 4 | + * @param queue |
| 5 | + * @param visited |
| 6 | + */ |
| 7 | +const bfs = (matrix: number[][], queue: number[][], visited: boolean[][]): void => { |
| 8 | + let m = matrix.length, n = matrix[0].length; |
| 9 | + let directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; |
| 10 | + |
| 11 | + while (queue.length > 0) { |
| 12 | + const [qCordx, qCordy] = queue.shift()!; |
| 13 | + for (let dir of directions) { |
| 14 | + const x = qCordx + dir[0], y = qCordy + dir[1]; |
| 15 | + if (!( |
| 16 | + x < 0 || |
| 17 | + y < 0 || |
| 18 | + x >= m || |
| 19 | + y >= n || |
| 20 | + visited[x][y] || |
| 21 | + matrix[x][y] < matrix[qCordx][qCordy]) |
| 22 | + ) { |
| 23 | + visited[x][y] = true; |
| 24 | + queue.push([x, y]); |
| 25 | + } |
| 26 | + |
| 27 | + } |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Creates a Matrix NXM with false values |
| 33 | + */ |
| 34 | +const createMatrix = (n: number, m: number): boolean[][] => |
| 35 | + Array.from({ length: n }, () => Array.from({ length: m }, () => false)); |
| 36 | + |
| 37 | + |
| 38 | +function pacificAtlantic(heights: number[][]): number[][] { |
| 39 | + const ROWS = heights.length, COLS = heights[0].length; |
| 40 | + let pacific: boolean[][] = createMatrix(ROWS, COLS); |
| 41 | + let atlantic: boolean[][] = createMatrix(ROWS, COLS); |
| 42 | + let pacQueue: number[][] = []; |
| 43 | + let atlQueue: number[][] = []; |
| 44 | + let results: number[][] = []; |
| 45 | + |
| 46 | + // Set as 'true' Pacific edges |
| 47 | + for (let i = 0; i < ROWS; i++) { |
| 48 | + pacific[i][0] = true; |
| 49 | + atlantic[i][COLS - 1] = true; |
| 50 | + atlQueue.push([i, COLS - 1]); |
| 51 | + pacQueue.push([i, 0]); |
| 52 | + } |
| 53 | + // Set as 'true' atlantic edges |
| 54 | + for (let j = 0; j < COLS; j++) { |
| 55 | + pacific[0][j] = true; |
| 56 | + atlantic[ROWS - 1][j] = true; |
| 57 | + atlQueue.push([ROWS - 1, j]); |
| 58 | + pacQueue.push([0, j]); |
| 59 | + } |
| 60 | + |
| 61 | + // BFS |
| 62 | + bfs(heights, pacQueue, pacific); |
| 63 | + bfs(heights, atlQueue, atlantic); |
| 64 | + |
| 65 | + // Verify intersections |
| 66 | + for (let i = 0; i < ROWS; i++) { |
| 67 | + for (let j = 0; j < COLS; j++) { |
| 68 | + if (pacific[i][j] && atlantic[i][j]) results.push([i, j]); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + return results; |
| 73 | +}; |
0 commit comments