diff --git a/node-concepts/src/leetcodes/index.ts b/node-concepts/src/leetcodes/index.ts index 94e3580..81ea7c1 100644 --- a/node-concepts/src/leetcodes/index.ts +++ b/node-concepts/src/leetcodes/index.ts @@ -1,3 +1,4 @@ +import { NumberOfIslands } from './src/number-of-islands'; import { Numbers } from './src/numbers'; Numbers.swapNumber(2, 4); @@ -5,3 +6,5 @@ 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(); diff --git a/node-concepts/src/leetcodes/src/graph/graph.ts b/node-concepts/src/leetcodes/src/graph/tree.ts similarity index 100% rename from node-concepts/src/leetcodes/src/graph/graph.ts rename to node-concepts/src/leetcodes/src/graph/tree.ts diff --git a/node-concepts/src/leetcodes/src/number-of-islands/index.ts b/node-concepts/src/leetcodes/src/number-of-islands/index.ts index 871f941..bc54230 100644 --- a/node-concepts/src/leetcodes/src/number-of-islands/index.ts +++ b/node-concepts/src/leetcodes/src/number-of-islands/index.ts @@ -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 } }