diff --git a/src/count-islands/index.js b/src/count-islands/index.js index ec88f6b..5611b39 100644 --- a/src/count-islands/index.js +++ b/src/count-islands/index.js @@ -1,3 +1,32 @@ -function countIslands(grid) {} +const countIslands = grid => { + + // Destroy the islands + const purgeIslandsFound = (row, col) => { + // Base case + if (row < 0 || col < 0 || row >= grid.length || col >= grid[row].length || grid[row][col] == 0) { + return; + } + // mark as visited + grid[row][col] = 0; + + // Recursive case for neighbours + purgeIslandsFound(row - 1, col); //up + purgeIslandsFound(row + 1, col); //down + purgeIslandsFound(row, col - 1); //left + purgeIslandsFound(row, col + 1); //down + } + + // Check for islands in each grids + let islands = 0 + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[i].length; j++) { + if (grid[i][j] === 1) { + islands++ + purgeIslandsFound(i, j) + } + } + } + return islands +} module.exports = countIslands; diff --git a/src/word-search/index.js b/src/word-search/index.js index 2e385e5..92e3d55 100644 --- a/src/word-search/index.js +++ b/src/word-search/index.js @@ -1,3 +1,36 @@ -function wordSearch(words, word) {} +const wordSearch = (board, word) => { + + let result = false; + const transvereGrid = (row, col, i) => { + if (!result) { + //base case + if (row < 0 || col < 0 || row >= board.length || col >= board[0].length) return; + if (board[row][col] != word[i]) return; // wrong character, over + if (i == word.length - 1) { // found a correct path + result = true; + return; + } + board[row][col] = null; // mark as visited + + //recursive case + transvereGrid(row + 1, col, i + 1) + transvereGrid(row - 1, col, i + 1) + transvereGrid(row, col + 1, i + 1) + transvereGrid(row, col - 1, i + 1) + board[row][col] = word[i] // reset board + } + } + + for (let i = 0; i < board.length; i++) { + for (let j = 0; j < board[0].length; j++) { + if (board[i][j] == word[0]) { + transvereGrid(i, j, 0) + if (result) return result; + } + } + } + + return result; +}; module.exports = wordSearch;