美文网首页Leetcode
Leetcode 200. Number of Islands

Leetcode 200. Number of Islands

作者: SnailTyan | 来源:发表于2018-10-26 18:30 被阅读1次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Number of Islands

    2. Solution

    class Solution {
    public:
        int numIslands(vector<vector<char>>& grid) {
            if(grid.size() == 0) {
                return 0;
            }
            int islands = 0;
            int rows = grid.size();
            int columns = grid[0].size();
            for(int i = 0; i < rows; i++) {
                for(int j = 0; j < columns; j++) {
                    if(grid[i][j] == '1') {
                        islands++;
                        removeIsland(grid, i, j, rows, columns);
                    }
                }
            }
            return islands;
        }
    
    private:
        void removeIsland(vector<vector<char>>& grid, int i, int j, int& rows, int& columns) {
            if(i < 0 || i == rows || j < 0 || j == columns || grid[i][j] == '0') {
                return;
            }
            grid[i][j] = '0';
            removeIsland(grid, i + 1, j, rows, columns);
            removeIsland(grid, i - 1, j, rows, columns);
            removeIsland(grid, i, j + 1, rows, columns);
            removeIsland(grid, i, j - 1, rows, columns);
        }
    };
    

    Reference

    1. https://leetcode.com/problems/number-of-islands/description/

    相关文章

      网友评论

        本文标题:Leetcode 200. Number of Islands

        本文链接:https://www.haomeiwen.com/subject/iyultqtx.html