diff --git a/src/count-islands/index.js b/src/count-islands/index.js index ec88f6b..8f737ad 100644 --- a/src/count-islands/index.js +++ b/src/count-islands/index.js @@ -1,3 +1,37 @@ -function countIslands(grid) {} +function countIslands(grid) { + let noOfRows = grid.length, noOfCols = grid[0].length; // matrix dimentions + + let noOfIslands = 0; + let visited = []; // grid of visited islands on the latest iterations + let left = 0, // island on the left + up = 0; // island on the right + + for (let row = 0; row < noOfRows; row++) { + for (let col = 0; col < noOfCols; col++) { + if (!grid[row][col]) { + continue; // skip zero (water) + } + left = col > 0 ? + grid[row][col - 1] : + 0; + + up = row > 0 ? + grid[row - 1][col] : + 0; + if (!left && !up) { // new island starts if there is water on the left and up + noOfIslands++; + grid[row][col] = noOfIslands; // give a number to island + } else if (left && up && left !== up) { //upper island is not seperate + grid[row][col] = left; + visited.push(up) + } else if (left) { + grid[row][col] = left; // island continues previous island to the right + } else if (up) { + grid[row][col] = up; // island continues previous island + } + } + } + return noOfIslands - visited.length; +} module.exports = countIslands; diff --git a/src/word-search/index.js b/src/word-search/index.js index 2e385e5..827dcdc 100644 --- a/src/word-search/index.js +++ b/src/word-search/index.js @@ -1,3 +1,31 @@ -function wordSearch(words, word) {} +function wordSeartemp(words, word) { + if (word === "") return true; -module.exports = wordSearch; + for (var row = 0; row < words.length; row++) { + for (var col = 0; col < words[row].length; col++) { + if (words[row][col] === word[0]) { + if (transversal(0, row, col)) return true; + } + } + } + return false; + function transversal(wordPosition, x, y) { + if (wordPosition === word.length) return true; + if (!words[x] || !words[x][y]) return false; + if (words[x][y] !== '%%' && words[x][y] === word[wordPosition]) { + let tempStorage = words[x][y]; + words[x][y] = '%%'; + + if (transversal(wordPosition + 1, x - 1, y)) return true; //up + if (transversal(wordPosition + 1, x + 1, y)) return true; //down + if (transversal(wordPosition + 1, x, y - 1)) return true; //left + if (transversal(wordPosition + 1, x, y + 1)) return true; //right + words[x][y] = tempStorage; // backtracking + } + return false; + } +}; + + + +module.exports = wordSeartemp;