diff --git a/src/count-islands/index.js b/src/count-islands/index.js index ec88f6b..63e1118 100644 --- a/src/count-islands/index.js +++ b/src/count-islands/index.js @@ -1,3 +1,30 @@ -function countIslands(grid) {} +const wordSearch = require("../word-search"); +function countIslands(grid) { + + var count = 0; + let n = grid.length; + if (n == 0) return 0; + let m = grid[0].length; + + for (let i = 0; i < n; i++) { + for (let j = 0; j < m; j++) + if (grid[i][j] == '1') { + DFS(grid, i, j); + ++count; + } + } + return count;}; + + function DFS(grid, row, col) { + if (row < 0 || col < 0 || row >= grid.length || col >= grid[0].length || grid[row][col] != '1') return; + grid[row][col] = '0'; + DFS(grid, row + 1, col); + DFS(grid, row - 1, col); + DFS(grid, row, col + 1); + DFS(grid, row, col - 1); +} + + + module.exports = countIslands; diff --git a/src/word-search/index.js b/src/word-search/index.js index 2e385e5..87e5669 100644 --- a/src/word-search/index.js +++ b/src/word-search/index.js @@ -1,3 +1,33 @@ -function wordSearch(words, word) {} +function wordSearch(words, word) { + + if(word ===" ") return true; + for(let row = 0;row < words.length; row++){ + for(let col = 0; col < words[row].length; col++){ + if(words[row][col] === word[0]){ + if(search(0, row, col)) + return true; + } + } + } + return false; + + function search(index, x, y){ + if(index === word.length) return true; + if(!words[x] || !words[x][y]) return false; + + if(words[x][y] !== '#' && words[x][y] === word[index]){ + let letter = words[x][y]; + words[x][y] = '#'; + + if(search(index+1, x - 1, y)) return true; + if(search(index+1, x + 1, y)) return true; + if(search(index+1, x , y - 1)) return true; + if(search(index+1, x , y + 1)) return true; + + words[x][y] = letter; + } + return false; + } +} module.exports = wordSearch;