LeetCode/463. Island Perimeter.md
2018-09-18 23:28:02 +08:00

1.2 KiB
Raw Blame History

463. Island Perimeter

思路

求”小岛”的周长,题目给了一些“小岛”的限制条件,例如小岛没有“湖”、“小岛”都是由方块上下连接的等等。
我们只需要遍历一遍grid对于每个方块根据是否是边界和周围方块的情况进行合适的周长累加即可。
时间复杂度O(n)

C++

class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        int dx[4] = {1, -1, 0, 0};
        int dy[4] = {0, 0, 1, -1};
        int r = grid.size(), c = grid[0].size(), res = 0, x, y;
        for(int i = 0; i < r; i++)
            for(int j = 0; j < c; j++){
                if(grid[i][j] == 0) continue;
                if(i == 0) res++;
                if(i == (r - 1)) res++;
                if(j == 0) res++;
                if(j == (c - 1)) res++;
                for(int k = 0; k < 4; k++){ // 上下左右
                    x = i + dx[k];
                    y = j + dy[k];
                    if(!(x < 0 || x >= r || y < 0 || y >= c) && grid[x][y] == 0) res++;   
                }
            }
        return res;
    }
};