📜  RiverSizes javascript (1)

📅  最后修改于: 2023-12-03 15:19:49.852000             🧑  作者: Mango

RiverSizes JavaScript

Description

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.

Usage
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 ]
Complexity
  • Time complexity: O(N * M) where N is the number of rows and M is the number of columns in the matrix
  • Space complexity: O(N * M) where N is the number of rows and M is the number of columns in the matrix
Explanation

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.

References