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
31 changes: 30 additions & 1 deletion src/count-islands/index.js
Original file line number Diff line number Diff line change
@@ -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;
35 changes: 34 additions & 1 deletion src/word-search/index.js
Original file line number Diff line number Diff line change
@@ -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;