# 2ms Java Solution

• ``````public class Solution {
public int curr_x;
public int curr_y;
public int result;

public int numIslands(char[][] grid) {
result = 0;
curr_x = 0;
curr_y = 0;
/*
1 -- init 1
0 -- init 0
2 -- traversed 1

*/
while (curr_x < grid.length && curr_y < grid[0].length) {

find_one(grid);

DFS(grid, curr_x, curr_y);

}

return result;
}

public void find_one(char[][] grid) {
while ( (curr_x <= grid.length-1 && curr_y <= grid[0].length -1) &&
grid[curr_x][curr_y] != '1' ) {
if (curr_y != grid[0].length -1) {
curr_y++;
} else {
curr_x++;
curr_y = 0;
}

}
if ((curr_x <= grid.length-1 && curr_y <= grid[0].length -1) &&
grid[curr_x][curr_y] == '1') {
result ++;
}
}

public void DFS(char[][] grid, int x, int y) {
if (x < 0 || x > grid.length - 1 ||
y < 0 || y > grid[x].length - 1) {
return;
}
if (grid[x][y] != '1') {
return;
}

grid[x][y] = '2';
DFS(grid, x + 1,y);
DFS(grid, x - 1,y);
DFS(grid, x, y + 1);
DFS(grid, x, y - 1);
return;
}
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.