Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

463. Island Perimeter #249

Open Tcdian opened 4 years ago

Tcdian commented 4 years ago

463. Island Perimeter

给定一个包含 01 的二维网格地图,其中 1 表示陆地 0 表示水域。

网格中的格子水平和垂直方向相连(对角线方向不相连)。整个网格被水完全包围,但其中恰好有一个岛屿(或者说,一个或多个表示陆地的格子相连组成的岛屿)。

岛屿中没有“湖”(“湖” 指水域在岛屿内部且不和岛屿周围的水相连)。格子是边长为 1 的正方形。网格为长方形,且宽度和高度均不超过 100 。计算这个岛屿的周长。

Example

Input:

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

Output: 16

Explanation: The perimeter is the 16 yellow stripes in the image below:

Tcdian commented 4 years ago

Solution

/**
 * @param {number[][]} grid
 * @return {number}
 */
var islandPerimeter = function(grid) {
    let perimeter = 0;
    const direction = [-1, 0, 1, 0, -1];
    for (let i = 0; i < grid.length; i++) {
        for (let j = 0; j < grid[0].length; j++) {
            if (grid[i][j] === 1) {
                for (let d = 0; d < 4; d++) {
                    const directionX = i + direction[d];
                    const directionY = j + direction[d + 1];
                    if (
                        directionX < 0 || directionX >= grid.length
                            || directionY < 0 || directionY >= grid[0].length
                            || grid[directionX][directionY] === 0
                    ) {
                        perimeter += 1;
                    }
                }
            }
        }
    }
    return perimeter;
};
function islandPerimeter(grid: number[][]): number {
    let perimeter = 0;
    const direction = [-1, 0, 1, 0, -1];
    for (let i = 0; i < grid.length; i++) {
        for (let j = 0; j < grid[0].length; j++) {
            if (grid[i][j] === 1) {
                for (let d = 0; d < 4; d++) {
                    const directionX = i + direction[d];
                    const directionY = j + direction[d + 1];
                    if (
                        directionX < 0 || directionX >= grid.length
                            || directionY < 0 || directionY >= grid[0].length
                            || grid[directionX][directionY] === 0
                    ) {
                        perimeter += 1;
                    }
                }
            }
        }
    }
    return perimeter;
};