I have similar solution and same problem. Here is my code:

class Solution {
int[][] dirs = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
public int findCircleNum(int[][] M) {
if(M == null)
return 0;
int m = M.length;
int n = M[0].length;
boolean[][] visited = new boolean[m][n];
int count = 0;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(M[i][j] == 1 && !visited[i][j]){
count++;
dfs(M, visited, i, j);
}
}
}
return count;
}
public void dfs(int[][] M, boolean[][] visited, int i, int j){
int m = M.length;
int n = M[0].length;
if(i<0 || i>=m || j<0 || j>=n || visited[i][j] || M[i][j] == 0)
return;
visited[i][j] = true;
for(int[] dir : dirs){
dfs(M, visited, i+dir[0], j+dir[1]);
}
}

}

Please, let me know if you find the reason/solution?