July LeetCoding Challenge - 7

이선태·2020년 7월 7일
0

Leetcode challenge

목록 보기
7/8

Day 7

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:

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:

답(Java)

class Solution {
    public int islandPerimeter(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int perimeter = 0;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 0)
                    continue;
                if (i == 0 || grid[i-1][j] == 0)
                    perimeter++;
                if (i == m-1 || grid[i+1][j] == 0)
                    perimeter++;
                if (j == 0 || grid[i][j-1] == 0)
                    perimeter++;
                if (j == n-1 || grid[i][j+1] == 0)
                    perimeter++;
            }
        }
        return perimeter;
    }
}

perimeter는 각 island에서 lake와 이웃하거나 grid 끝 방향에서만 계산된다. grid에서 island를 찾아 island의 상, 하, 좌, 우 4 방향을 탐색하여 lake가 있는지 또는 grid의 끝인지를 검사한다. 조건을 만족하면 perimeter가 존재할 수 있으므로 perimeter 변수를 증가시킨다.

profile
퀀트 트레이딩, 통계에 관심이 많아요

0개의 댓글