So basically I am trying to solve the 200. Number of Islands Leetcode challenge but I keep getting the above error. I know what the error implies but I can't spot the situation in my code. I have both a test file and the actual code file. There is an inner loop and recursion and the error keeps happening at the recursion function
index.js
function numIslands(grid) {
let count = 0;
//we would iterate over every cell in the matrix
//we start by iterating over the row
for (let row = 0; row < grid.length; row++) {
//then iterate over column.
//We use grid[0].length becuase all col at the same so we just take the first length
for (let col = 0; col < grid[0].length; col++) {
//if the current cell is 1
if (grid[row][col] === '1') {
//sink the island if a o
count++;
//this function is to sink the island
//i.e turn to
dfs(grid, row, col);
}
}
}
function dfs(grid, row, col) {
//if row is less than 0 or out of bounds
//if col is less than 0 or out of bounds vertically
// or current cell is water, then end the function call,
if (row < 0 || row >= grid.length || col < 0 || col >= grid[0].length || grid[row][col] === '0') {
return;
}
//|| row >= grid.length || col < 0 || col >= grid[0].length || grid[row][col] === '0'
// set the current cell to 0, i.e sink it
grid[row][col] === '0';
//check the cells to the left right top and bottom of current cell
dfs(grid, row - 1, col); //left
dfs(grid, row + 1, col); //right
dfs(grid, row, col - 1); ///bottom
dfs(grid, row, col + 1); ///top
}
return count;
}
test file
test("returns 0 islands correctly.", () => {
expect(
numIslands([
["0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0"]
])
).toEqual(0);
});
test("returns 1 island correctly.", () => {
expect(
numIslands([
["1", "1", "1", "1", "0"],
["1", "1", "0", "1", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0"]
])
).toEqual(1);
});
test("returns 3 islands correctly.", () => {
expect(
numIslands([
["1", "1", "0", "0", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "1", "0", "0"],
["0", "0", "0", "1", "1"]
])
).toEqual(3);
});