📅  最后修改于: 2023-12-03 15:19:49.852000             🧑  作者: Mango
RiverSizes is a JavaScript function that takes in a two-dimensional array (matrix) and returns an array of the sizes of all the rivers in the matrix.
A river consists of adjacent 1s (in any row or column) that are connected either vertically or horizontally. The size of a river is the number of 1s it contains.
const riverSizes = require('./riverSizes.js');
const matrix = [
[1, 0, 0, 1, 0],
[1, 0, 1, 0, 0],
[0, 0, 1, 0, 1],
[1, 0, 1, 0, 1],
[1, 0, 1, 1, 0]
];
const result = riverSizes(matrix);
console.log(result); // [ 2, 1, 5, 2 ]
We can use a modified depth-first search approach to find all the rivers in the matrix. Starting at any 1, we traverse all its adjacent 1s (i.e., the ones above, below, to the left, and to the right of it) and mark them as visited. We continue this process until we have found all the 1s in the current river.
Once we have found all the 1s in a river, we add its size to our result array and move on to the next unvisited 1 in the matrix. We repeat this process until we have visited all the 1s in the matrix.