|
| 1 | +/** |
| 2 | + * River Sizes |
| 3 | + * You are given a two-dimensional array (matrix) of potentially unequal height and width containing only 0s and 1s. Each 0 represents land, and each 1 represents part of a river. A river consists of any number of 1s that are either horizontally or vertically adjacent (but not diagonally adjacent). The number of adjacent 1s forming a river determine its size. Write a function that returns an array of the sizes of all rivers represented in the input matrix. Note that these sizes do not need to be in any particular order. |
| 4 | + * |
| 5 | + * Sample input: |
| 6 | + * [ |
| 7 | + * [1,0,0,1,0], |
| 8 | + * [1,0,1,0,0], |
| 9 | + * [0,0,1,0,1], |
| 10 | + * [1,0,1,0,1], |
| 11 | + * [1,0,1,1,0] |
| 12 | + * ] |
| 13 | + * |
| 14 | + * Sample output: |
| 15 | + * [2,1,5,2,2] |
| 16 | + */ |
| 17 | + |
| 18 | + |
| 19 | +function riverSizes(matrix) { |
| 20 | + const rows = matrix.length; |
| 21 | + const cols = matrix[0].length; |
| 22 | + const sizes = []; |
| 23 | + |
| 24 | + for (let i = 0; i < rows; i++) { |
| 25 | + for (let j = 0; j < cols; j++) { |
| 26 | + if (matrix[i][j] === 1) { |
| 27 | + visitRiver(i, j, matrix, sizes, rows, cols); |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + return sizes; |
| 33 | +} |
| 34 | + |
| 35 | +function visitRiver(i, j, matrix, sizes, rows, cols) { |
| 36 | + let count = 0; |
| 37 | + const stack = [[i, j]]; |
| 38 | + |
| 39 | + while (stack.length) { |
| 40 | + const node = stack.shift(); |
| 41 | + const i = node[0]; |
| 42 | + const j = node[1]; |
| 43 | + |
| 44 | + if (matrix[i][j] === 1) { |
| 45 | + matrix[i][j] = 3; |
| 46 | + |
| 47 | + count++; |
| 48 | + |
| 49 | + stack.push(...getNearbyRiver(i, j, rows, cols, matrix)); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + if (count > 0) { |
| 54 | + sizes.push(count); |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +function getNearbyRiver(i, j, rows, cols, matrix) { |
| 59 | + const available = []; |
| 60 | + |
| 61 | + // Top |
| 62 | + if (i > 0 && i < rows && matrix[i - 1][j] === 1) { |
| 63 | + available.push([i - 1, j]); |
| 64 | + } |
| 65 | + |
| 66 | + // Bottom |
| 67 | + if (i >= 0 && i < rows - 1 && matrix[i + 1][j] === 1) { |
| 68 | + available.push([i + 1, j]); |
| 69 | + } |
| 70 | + |
| 71 | + // Left |
| 72 | + if (j > 0 && j < cols && matrix[i][j - 1] === 1) { |
| 73 | + available.push([i, j - 1]); |
| 74 | + } |
| 75 | + |
| 76 | + // Right |
| 77 | + if (j >= 0 && j < cols - 1 && matrix[i][j + 1] === 1) { |
| 78 | + available.push([i, j + 1]); |
| 79 | + } |
| 80 | + |
| 81 | + return available; |
| 82 | +} |
| 83 | + |
| 84 | + |
| 85 | +const input = [ |
| 86 | + [1,0,0,1,0], |
| 87 | + [1,0,1,0,0], |
| 88 | + [0,0,1,0,1], |
| 89 | + [1,0,1,0,1], |
| 90 | + [1,0,1,1,0] |
| 91 | +]; |
| 92 | + |
| 93 | +console.log(riverSizes(input)); |
0 commit comments