2023年1月23日 星期一

200. Number of Islands

解題思路

每當找到一個沒看過的島,就四方探索整個範圍並且把該位置抹掉。

程式碼

class Solution {
public:
    void bfs(vector<vector<char>>& grid, int x, int y)
    {
        int dx[4] = {-1, 0, 0, 1}, dy[4] = {0, 1, -1, 0};
        if(0 <= x && x < grid.size() && 0 <= y && y < grid[0].size() && grid[x][y] == '1')
        {
            grid[x][y] = '0';
            for(int i=0; i<4; i++)
                bfs(grid, x+dx[i], y+dy[i]);
        }
    }
    int numIslands(vector<vector<char>>& grid) {
        int num = 0;

        for(int i=0; i<grid.size(); i++)
        {
            for(int j=0; j<grid[0].size(); j++)
            {
                if(grid[i][j] == '1')
                {
                    num++;
                    bfs(grid, i, j);
                }
            }
        }
        return num;
    }
};

沒有留言:

張貼留言