var numIslands = function (grid) {
const rows = grid.length;
const columns = grid[0].length;
const directions = [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
];
let count = 0;
const bfs = (startRow, startColumn) => {
const queue = [[startRow, startColumn]];
let head = 0;
// 入队时立即标记,避免被相邻格重复入队
grid[startRow][startColumn] = "0";
while (head < queue.length) {
const [row, column] = queue[head++];
for (const [rowOffset, columnOffset] of directions) {
const nextRow = row + rowOffset;
const nextColumn = column + columnOffset;
const isInGrid =
nextRow >= 0 &&
nextRow < rows &&
nextColumn >= 0 &&
nextColumn < columns;
if (isInGrid && grid[nextRow][nextColumn] === "1") {
grid[nextRow][nextColumn] = "0";
queue.push([nextRow, nextColumn]);
}
}
}
};
for (let row = 0; row < rows; row++) {
for (let column = 0; column < columns; column++) {
if (grid[row][column] === "1") {
count++;
bfs(row, column);
}
}
}
return count;
};