1. 程式人生 > 資訊 >李子柒:火了以後有 MCN 找過來,推廣成本共同承擔

李子柒:火了以後有 MCN 找過來,推廣成本共同承擔

題目連結:https://leetcode-cn.com/problems/number-of-islands
題目描述:
給你一個由'1'(陸地)和 '0'(水)組成的的二維網格,請你計算網格中島嶼的數量。
島嶼總是被水包圍,並且每座島嶼只能由水平方向和/或豎直方向上相鄰的陸地連線形成。
此外,你可以假設該網格的四條邊均被水包圍。

示例 1:
輸入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
輸出:1

示例 2:
輸入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
輸出:3

提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] 的值為 '0' 或 '1'

題解:

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
       int ans = 0;
       for(int i = 0; i < grid.size(); i++)
       {
           for(int j = 0; j < grid[0].size(); j++)
           {
               if(grid[i][j] == '1')
               {
                   ans++; 
                   dfs(grid, i, j);
               }
           }
       }
       return ans;
    }
    void dfs(vector<vector<char>>& grid, int r, int c)
    {
        //base 判斷是否越界
        if(!isLands(grid, r, c))
            return;
        if(grid[r][c] != '1')
            return;
        //標記已經訪問過的點
        grid[r][c] = '2';
        //遍歷周圍點
        dfs(grid, r - 1, c);
        dfs(grid, r + 1, c);
        dfs(grid, r, c - 1);
        dfs(grid, r, c + 1);
    }
    bool isLands(vector<vector<char>>& grid, int r, int c)
    {
        return (r >= 0 && r < grid.size() && c >= 0 && c <grid[0].size());
    }
};