[LeetCode-463]Island Perimeter

You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn’t have “lakes” (water inside that isn’t connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don’t exceed 100. Determine the perimeter of the island.

Example:

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

Answer: 16

public int islandPerimeter(int[][] grid) {
        if(grid == null || grid.length == 0) return 0;

        int row = grid.length, col = grid[0].length;
        //存储每一列边数
        int[] colSum = new int[col];
        //存储每一行边数
        int[] rowSum = new int[row];

        colSum[0] = rowSum[0] = grid[0][0] == 1 ? 2 : 0;
        //处理第一行
        for(int i = 1; i < row; i++) {
            if(grid[i][0] == 1) {
                colSum[0] += grid[i - 1][0] == 0 ? 2 : 0;
                rowSum[i] += 2;
            }
        }
        //处理第一列
        for(int i = 1; i < col; i++) {
            if(grid[0][i] == 1) {
                rowSum[0] += grid[0][i - 1] == 0 ? 2 : 0;
                colSum[i] += 2;
            }
        }

        for(int i = 1; i < row; i++) {
            for(int j = 1; j < col; j++) {
                if(grid[i][j] == 1){
                    if(grid[i - 1][j] == 0) colSum[j] += 2;
                    if(grid[i][j - 1] == 0) rowSum[i] += 2;
                }
            }
        }

        int res = 0;
        for(int i : rowSum) res += i;
        for(int i : colSum) res += i;

        return res;
    }

你可能感兴趣的:(leetcode)