// Условие:
// Дана двумерная матрица grid, состоящая из символов:
// '1' — земля
// '0' — вода
// Нужно посчитать, сколько отдельных островов находится в матрице.
// 👉 Остров — это группа '1', соединённых по сторонам:
// вверх
// вниз
// влево
// вправо
const countIslands = matrix => {
let islands = 0;
const drownIsland = (row, col) => {
matrix[row][col] = 0;
if (matrix[row - 1] && matrix[row - 1][col] == 1) drownIsland(row - 1, col);
if (matrix[row + 1] && matrix[row + 1][col] == 1) drownIsland(row + 1, col);
if (matrix[row][col - 1] == 1) drownIsland(row, col - 1);
if (matrix[row][col + 1] == 1) drownIsland(row, col + 1);
};
for (let i = 0; i < matrix.length; i++) {
const row = matrix[i];
for (let j = 0; j < row.length; j++) {
if (matrix[i][j] == 1) {
islands++;
drownIsland(i, j);
}
}
}
return islands;
};
console.log(
countIslands([
['1', '1', '0', '0'],
['1', '1', '0', '0'],
['0', '0', '1', '0'],
['0', '0', '0', '1'],
])
); // 3
console.log(countIslands([
['1', '1', '1'],
['0', '1', '0'],
['1', '1', '1']])); // 1
console.log(countIslands([
[1, 1, 0],
[1, 0, 1],
[0, 1, 1]])); // 2
Click Run to execute JavaScript.
Code runs in an isolated environment.
Code runs in an isolated environment.