Max Area of Island(leetcode)

来源:互联网 发布:淘宝拍照用什么手机 编辑:程序博客网 时间:2024/06/05 21:09

Max Area of Island

  • Max Area of Island
    • 题目
    • 解决


题目

Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

Example 1:

[[0,0,1,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,1,1,0,1,0,0,0,0,0,0,0,0], [0,1,0,0,1,1,0,0,1,0,1,0,0], [0,1,0,0,1,1,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,0,1,1,0,0,0,0]]

Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.

Example 2:

[[0,0,0,0,0,0,0,0]]

Given the above grid, return 0.

Note: The length of each dimension in the given grid does not exceed 50.


解决

class Solution {public:    int maxAreaOfIsland(vector<vector<int>>& grid) {        int result = 0;        int row = grid.size();        if (row == 0) return result;        int col = grid[0].size();        for (int i = 0; i < row; i++) {            for (int j = 0; j < col; j++) {                if (grid[i][j] == 1) {                // 判断grid[i][j]附近是否存在着相邻的 土地                    int temp = searchArea(grid, i, j);                    result = (result < temp) ? temp : result;                }            }        }        return result;    }    int searchArea(vector<vector<int>>& grid, int i, int j) {        int result = 0;        int row = grid.size();        if (row == 0) return result;        int col = grid[0].size();        if (i >= 0 && i < row && j >= 0 && j < col && grid[i][j] == 1) {            grid[i][j] = -1; // 将数过的土地作标志,避免重复数数            // 计算附近相邻土地数量            result = searchArea(grid, i + 1, j) + searchArea(grid, i - 1, j) + searchArea(grid, i, j + 1) + searchArea(grid, i, j - 1);            return result + 1;        }        return result;    }};
原创粉丝点击