Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion src/count-islands/index.js
Original file line number Diff line number Diff line change
@@ -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;
32 changes: 30 additions & 2 deletions src/word-search/index.js
Original file line number Diff line number Diff line change
@@ -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;