題目要求:
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
題目大意:給定一個2維數組,0代表水强饮,1代表陸地陨献,求島嶼的數量淮菠,相鄰的陸地算一個島嶼。
比如:
image.png
上圖 島嶼數為 3
大概思路:用一個二維 bool 數組作為輔助數組居夹,用來標記該節(jié)點是否訪問過荆忍,然后循環(huán)遍歷原數組中的每個節(jié)點,如果該節(jié)點的值為1囊蓝,且沒有被訪問過饿悬,則島嶼數 +1,然后對該島嶼上下左右進行深度遍歷聚霜,只標記而不增加島嶼數狡恬。
代碼如下:
public static int numIslands(char[][] grid) {
if(grid.length < 1) return 0;
int count = 0;
boolean [][] searched = new boolean[grid.length][grid[0].length];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if(grid[i][j] == '0' || searched[i][j] == true) continue;
count += 1;
dfs(grid,searched,i,j);
}
}
return count;
}
public static void dfs(char[][]grid,boolean [][] used,int i,int j){
if(grid[i][j] == '0' || used[i][j] == true) return;
used[i][j] = true;
if(i < grid.length-1) dfs(grid,used,i+1,j);
if(i > 0) dfs(grid,used,i-1,j);
if(j < grid[0].length -1) dfs(grid,used,i,j+1);
if(j > 0) dfs(grid,used,i,j-1);
}