Skip to content

Update 0200-number-of-islands.ts #2345

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 21 additions & 46 deletions typescript/0200-number-of-islands.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,29 @@
//BFS way to solve this
const bfs = (grid, r, c) => {
const [ROWS, COLS] = [grid.length, grid[0].length];

const directions = [
[-1, 0],
[1, 0],
[0, -1],
[0, 1],
];

let queue = [[r, c]];

//marks as visited
grid[r][c] = '0';

while (queue.length > 0) {
//dequeues the first element(current)
let [cr, cc] = queue.shift();

directions.forEach(([dr, dc]) => {
let [nr, nc] = [cr + dr, cc + dc];
if (
!(
nr < 0 ||
nc < 0 ||
nr >= ROWS ||
nc >= COLS ||
grid[nr][nc] === '0'
)
) {
queue.push([nr, nc]);
grid[nr][nc] = '0';
}
});
const dfs = (grid: string[][], i: number, j: number) => {
if (
i < 0 ||
j < 0 ||
i >= grid.length ||
j >= grid[0].length ||
grid[i][j] == '0'
) {
return;
}
grid[i][j] = '0';
dfs(grid, i + 1, j);
dfs(grid, i, j + 1);
dfs(grid, i - 1, j);
dfs(grid, i, j - 1);
};

function numIslands(grid: string[][]): number {
const [ROWS, COLS] = [grid.length, grid[0].length];

let islands = 0;

for (let i = 0; i < ROWS; i++) {
for (let j = 0; j < COLS; j++) {
if (grid[i][j] === '1') {
bfs(grid, i, j);
islands++;
let count: number = 0;
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
dfs(grid, i, j);
count++;
}
}
}

return islands;
return count;
}