首页 > 代码库 > [LeetCode] 463 Island Perimeter

[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
Explanation: The perimeter is the 16 yellow stripes in the image below:

技术分享


解法:如果只有一个点,那么周长就是4,如果这个点和其他的一个点相邻,那么对于周长的贡献就要少一。同理,对于另外一个相邻的点,那么
贡献的周长也少一。于是先遍历,看看有多少个为1的点,算出“最大”的周长以后,减去因为相邻而减少的周长长度就可以了。

public int islandPerimeter(int[][] grid) {
        boolean[][] mark = new boolean[grid.length][grid[0].length];
        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    mark[i][j] = true;
                    count++;
                } else {
                    mark[i][j] = false;
                }
            }
        }
        int perimeter = count * 4;
        System.out.println("perimeter:" + perimeter);
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (mark[i][j]) {
                    perimeter -= neigbors(i, j, mark); //减去相邻的点
                }
            }
        }
        return perimeter;
    }


    private int neigbors(int i, int j, boolean[][] mark) {
        int count = 0;
        for (int x = -1; x <= 1; x += 2) {
            int tempx = x + i;
            int tempy = j;
            if (isSafe(tempx, tempy, mark.length, mark[0].length) && mark[tempx][tempy]) {
                count++;
            }
        }
        for (int y = -1; y <= 1; y += 2) {
            int tempx = i;
            int tempy = y + j;
            if (isSafe(tempx, tempy, mark.length, mark[0].length) && mark[tempx][tempy]) {
                count++;
            }
        }
        System.out.printf("i:%d,j:%d\n", i, j);
        System.out.println("count:" + count);
        return count;
    }

    private boolean isSafe(int x, int y, int xlength, int ylength) {
        if (x < 0 || x >= xlength || y < 0 || y >= ylength) {
            return false;
        } else {
            return true;
        }
    }

 

[LeetCode] 463 Island Perimeter