diff --git a/src/count-islands/index.js b/src/count-islands/index.js index ec88f6b..2a132b0 100644 --- a/src/count-islands/index.js +++ b/src/count-islands/index.js @@ -1,3 +1,30 @@ -function countIslands(grid) {} +function countIslands(grid) { + // if(grid.length === 0 || grid === null) { + // return 0 + // } + + let count = 0 + for(let row = 0; row < grid.length; row++) { + for(let col = 0; col < grid[row].length; col++) { + debugger; + if(grid[row][col] === 1) { + count++ + search(grid, row, col) + } + } + } + return count + + function search(grid, row, col) { + if(grid[row] === undefined || grid[row][col] === undefined || grid[row][col] === 0) return + + grid[row][col] = 0 + + search(grid, row - 1, col) + search(grid, row + 1, col) + search(grid, row, col - 1) + search(grid, row, col + 1) + } +} module.exports = countIslands; diff --git a/src/count-islands/test.js b/src/count-islands/test.js index 4ee76ba..e36a220 100644 --- a/src/count-islands/test.js +++ b/src/count-islands/test.js @@ -25,12 +25,10 @@ describe("Count Islands", () => { test("4x4 island", () => { const grid = [ - [ - [1, 1, 0, 0], - [0, 0, 1, 0], - [0, 0, 0, 1], - [0, 1, 0, 0], - ], + [1, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1], + [0, 1, 0, 0], ]; expect(countIslands(grid)).toBe(4); diff --git a/src/word-search/index.js b/src/word-search/index.js index 2e385e5..7c5d946 100644 --- a/src/word-search/index.js +++ b/src/word-search/index.js @@ -1,3 +1,28 @@ -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, row1, col1) { + if(index === word.length) return true + if(!words[row1] || !words[row1][col1]) return false + if(words[row1][col1] !== "#" && words[row1][col1] === word[index]) { + words[row1][col1] = "#" + + if(search(index + 1, row1 - 1, col1)) return true + if(search(index + 1, row1 + 1, col1)) return true + if(search(index + 1, row1, col1 - 1)) return true + if(search(index + 1, row1, col1 + 1)) return true + } + return false + } +} module.exports = wordSearch;