Leetcode 463. Island Perimeter

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/83419827

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

1. Description

Island Perimeter

2. Solution

class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        int perimeter = 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]) {
                    getPerimeter(grid, i, j, perimeter, rows, columns);
                    return perimeter;
                }
            }
        }
    }
private:
    void getPerimeter(vector<vector<int>>& grid, int i, int j, int& perimeter, int& rows, int& columns) {
        if(i < 0 || i == rows || j < 0 || j == columns || grid[i][j] == 0) {
            perimeter++;
            return;
        }
        if(grid[i][j] == -1) {
            return;
        }
        grid[i][j] = -1;
        getPerimeter(grid, i + 1, j, perimeter, rows, columns);
        getPerimeter(grid, i - 1, j, perimeter, rows, columns);
        getPerimeter(grid, i, j + 1, perimeter, rows, columns);
        getPerimeter(grid, i, j - 1, perimeter, rows, columns);
    }
};

Reference

  1. https://leetcode.com/problems/island-perimeter/description/

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试