200. 島嶼數量_中等_不再記筆記了

 

 

感覺把題解法和思路直接寫在LeetCode網站上就好了,寫博客麻煩了。

class Solution {

    int deleteIslands(int i,int j,char [][]grid,int [][]foot){
        foot[i][j] =1;
        if(grid[i][j] == '0')  return 0;
        else{
            grid[i][j] = '0';
            if(i<grid.length-1 && foot[i+1][j]==0){
                deleteIslands(i+1,j, grid,foot);
            }
            if(j<grid[0].length-1 && foot[i][j+1]==0){
                deleteIslands(i,j+1, grid,foot);
            }
            if(i>0 && foot[i-1][j]==0){
                deleteIslands(i-1,j, grid,foot);
            }
            if(j>0 && foot[i][j-1]==0){
                deleteIslands(i,j-1, grid,foot);
            }
            return 0;
        }
        
    }

    public int numIslands(char[][] grid) {
        int islandNum = 0;
        int foot[][] = new int[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]=='1'){
                 islandNum++;
                 deleteIslands(i,j,grid,foot);
             }
         }
     }
     return islandNum;    
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章