LeetCode知识点总结 - 463

LeetCode 463. Island Parameter

考点 难度
Array Easy
题目

You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 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”, meaning the water inside 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.

思路

从左上角方格开始算起(这里用到nested for loop),如果该方格是land则周长+4,如果该方格上面/左面的方格也是land则周长-2。
注意周长-2的前提条件是该方格是land,如果方格是water即使上面/左面的方格是land也不-2。
方向(左上/左下/右上/右下)不重要。

答案

答案1 (左上):

public static int islandPerimeter(int[][] grid) {
        int result = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    result += 4;
                    if (i > 0 && grid[i-1][j] == 1) result -= 2;
                    if (j > 0 && grid[i][j-1] == 1) result -= 2;
                }
            }
        }
        return result;
    }

答案2(右下)

public static int islandPerimeter(int[][] grid) {
        int result = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    result += 4;
                    if (i < grid.length - 1 && grid[i+1][j] == 1) result -= 2;
                    if (j < grid[0].length - 1 && grid[i][j+1] == 1) result -= 2;
                }
            }
        }
        return result;
    }

Guess you like

Origin blog.csdn.net/m0_59773145/article/details/120024481
Recommended