Skip to content

Commit

Permalink
add: number of islands
Browse files Browse the repository at this point in the history
  • Loading branch information
thutasann committed Sep 1, 2024
1 parent e22d84f commit 224f518
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 18 deletions.
3 changes: 3 additions & 0 deletions node-concepts/src/leetcodes/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { NumberOfIslands } from './src/number-of-islands';
import { Numbers } from './src/numbers';

Numbers.swapNumber(2, 4);
Numbers.swapNumberWithIndex(['a', 'b', 'c', 'd', 'e'], 1, 3);
Numbers.getSecondLargest([5, 1, 8, 3, 10, 7, 8]);
Numbers.reverseNumber(12345);
Numbers.sumOfNumber();

NumberOfIslands.usageOne();
65 changes: 47 additions & 18 deletions node-concepts/src/leetcodes/src/number-of-islands/index.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,59 @@
/* eslint-disable prefer-const */
export abstract class NumberOfIslands {
/** solution one */
public static solutionOne(grid: number[][]): number {
const visited = grid.map((row) => row.map((cell) => false));
/**
* Number of Island
* @param { string[][] } grid - Two Dimensional Array
* @returns { number }
*/
public static solutionOne(grid: string[][]): number {
let countIslands = 0;

let islandCount = 0;
for (let rowIndex in grid) {
for (let colIndex in grid[rowIndex]) {
console.log('grid[rowIndex][colIndex]', grid[rowIndex][colIndex]);

for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[i].length; j++) {
if (this.dFS(i, j, grid, visited)) islandCount++;
if (grid[rowIndex][colIndex] === '1') {
countIslands++;
this.teraform(parseInt(rowIndex), parseInt(colIndex), grid);
}
}
}

return islandCount;
return countIslands;
}

/** Usage */
public static usageOne() {
const result = this.solutionOne([
['1', '1', '0', '0', '0'],
['1', '1', '0', '0', '0'],
['0', '0', '1', '0', '0'],
['0', '0', '0', '1', '1'],
]);
console.log('Number of Islands : >>', result);
}

/** depth first search
/**
* Helper: Convert stuff arround us to Water
* @private
* @example
* - if returns true, means, we have an island
*/
private static dFS(
i: number,
j: number,
grid: number[][],
visited: boolean[][],
): boolean {
return true;
private static teraform(
rowIn: number,
colIn: number,
grid: string[][],
): void {
if (
grid[rowIn] === undefined ||
grid[rowIn][colIn] === undefined ||
grid[rowIn][colIn] === '0'
)
return;

grid[rowIn][colIn] = '0';

NumberOfIslands.teraform(rowIn + 1, colIn, grid); // top
this.teraform(rowIn - 1, colIn, grid); // bottom
this.teraform(rowIn, colIn + 1, grid); // right
this.teraform(rowIn, colIn - 1, grid); // left
}
}

0 comments on commit 224f518

Please sign in to comment.