島嶼數(shù)量

給定一個(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)生額外比較

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容