A description to the problem: https://leetcode.com/problems/number-of-islands/
Basically you have a matrix with 1s and 0s, and you need to count how many groups of 1s there are.
Despite many print statements, I can't figure out why this code is not working. I'm iterating through the matrix and anytime I see a one, I do a depth first search and turn that 1 plus all the 1s surrounding it to 0 - to mark those nodes as visited.
What are I missing?
class Solution {
public int numIslands(char[][] grid) {
int count = 0;
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[i].length; j++) {
//System.out.println(grid[i][j]);
if(grid[i][j] == '1') {
// System.out.println("i = " + i);
// System.out.println("j = " + j);
countIslands(grid, i, j);
count++;
}
}
}
return count;
}
public static void countIslands(char[][] grid, int sr, int sc) {
grid[sr][sc] = '0';
final int[][] SHIFTS = {
{0,1}, //move right
{1,0}, //move down
{0,-1}, //move left
{-1,0} //move up
};
for(int[] shift : SHIFTS) {
sr = sr + shift[0];
sc = sc + shift[1];
if(moveValid(grid, sr, sc)) {
countIslands(grid, sr, sc);
}
}
}
public static boolean moveValid(char[][] grid, int sr, int sc) {
if(sr >= 0 && sr < grid.length && sc >= 0 && sc < grid[sr].length && grid[sr][sc] == '1') {
return true;
}
return false;
}
}