计数的一些岛屿。一个岛,四面环水,是通过连接相邻的土地横向或纵向的形成。你可以假设所有四个边的网格都是被水包围。
1.检测是否被访问过了,如果是设置成x,然后取到下一格。
2.检查是否为1,如果不是,把它设置成已经访问过的,为x。
3.发现每一个岛中的1,然后增加岛的数目numisland,
去往从头开始的每个1,将它设置成已经访问过的,即设置成x
4.返回numisland。
时间复杂度为N,当n为矩阵的大小
空间复杂度为1,因为我们把它当作已访问的列表复用了矩阵。
1 public class Solution { 2 3 private void discoverIsland(char[][] g, int h, int w, int x, int y) 4 { 5 if( x < 0 || y < 0 || x >= h || y >= w ) return; 6 7 if( g[x][y] == 'x' || g[x][y] == '0' ) return; 8 9 g[x][y] = 'x'; 10 11 discoverIsland(g,h,w,x+1,y); 12 discoverIsland(g,h,w,x,y+1); 13 discoverIsland(g,h,w,x-1,y); 14 discoverIsland(g,h,w,x,y-1); 15 } 16 17 public int numIslands(char[][] grid) { 18 19 if( grid.length == 0 ) return 0; 20 21 int numIslands = 0; 22 int rows = grid.length; 23 int cols = grid[0].length; 24 for( int i=0; i<rows; i++ ) 25 { 26 for( int j=0; j<cols; j++ ) 27 { 28 if( grid[i][j] == 'x' ) continue; 29 30 if( grid[i][j] == '1' ) 31 { 32 discoverIsland(grid, rows, cols, i, j); 33 numIslands++; 34 } 35 else 36 { 37 grid[i][j] = 'x'; 38 } 39 } 40 } 41 42 return numIslands; 43 } 44 45 }
public class Solution {
void findIsland(char[][] grid, int x, int y, HashSet<Integer> used) {
int tag = 0;
int rows = grid.length;
int columns = grid[0].length;
// up
if (x > 0 && grid[x - 1][y] == '1') {
tag = (x - 1) * columns + y;
if (!used.contains(tag)) {
used.add(tag);
findIsland(grid, x - 1, y, used);
}
}
// right
if ( y < (columns - 1) && grid[x][y + 1] == '1') {
tag = x * columns + y + 1;
if (!used.contains(tag)) {
used.add(tag);
findIsland(grid, x, y + 1, used);
}
}
// down
if (x < (rows - 1) && grid[x + 1][y] == '1') {
tag = (x + 1) * columns + y;
if (!used.contains(tag)) {
used.add(tag);
findIsland(grid, x + 1, y, used);
}
}
// left
if(y > 0 && grid[x][y - 1] == '1') {
tag = x * columns + y - 1;
if (!used.contains(tag)) {
used.add(tag);
findIsland(grid, x, y - 1, used);
}
}
}
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
int result = 0;
int rows = grid.length;
int columns = grid[0].length;
HashSet<Integer> used = new HashSet<Integer>();
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns; ++j) {
if (grid[i][j] == '1') {
int tag = i * columns + j;
if (!used.contains(tag)) {
used.add(tag);
result ++;
findIsland(grid, i, j, used);
}
}
}
}
return result;
}
}