給定一個(gè)由 '1'(陸地)和 '0'(水)組成的的二維網(wǎng)格,計(jì)算島嶼的數(shù)量。一個(gè)島被水包圍,并且它是通過水平方向或垂直方向上相鄰的陸地連接而成的。你可以假設(shè)網(wǎng)格的四個(gè)邊均被水包圍。
示例 1:
輸入:
11110
11010
11000
00000
輸出: 1
示例 2:
輸入:
11000
11000
00100
00011
輸出: 3
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/number-of-islands
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
class Solution {
public int numIslands(char[][] grid) {
if(grid.length==0) return 0;
if(grid[0].length==0) return 0;
int width=grid.length;
int length=grid[0].length;
int count=0;
for (int i=0;i<width;i++){
for (int j=0;j<length;j++){
if(grid[i][j]=='1') {
count++;
search(i,j,grid,width,length);
}
}
}
return count;
}
private void search(int i,int j,char[][] grid,int width,int length){
if(i<0||i==width||j<0||j==length){
return;
}
if(grid[i][j]=='1') {
grid[i][j]='0';
search(i,j+1,grid,width,length);
search(i+1,j,grid,width,length);
search(i-1,j,grid,width,length);
search(i,j-1,grid,width,length);
}
}
}
注:開始的時(shí)候我是用的標(biāo)記法,將為1的地址進(jìn)行記錄,每次遍歷到1的時(shí)候看是否已經(jīng)放入記錄列表中,但是這種方法相對(duì)比標(biāo)記為0的方法會(huì)產(chǎn)生額外比較