[LeetCode] 463 Island Perimeter

황은하·2021년 8월 2일
0

알고리즘

목록 보기
79/100
post-thumbnail

Description

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.

Example 1:

Input: grid = [[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 above.

Example 2:

Input: grid = [[1]]
Output: 4

Example 3:

Input: grid = [[1,0]]
Output: 4

Constraints:

  • row == grid.length
  • col == grid[i].length
  • 1 <= row, col <= 100
  • grid[i][j] is 0 or 1.


풀이

그리드의 모든 셀을 한 칸씩 본다.

현재 셀이 0이면 넘어간다.

현재 셀이 1이면 상하좌우 칸을 살핀다.

만약 상하좌우의 셀이 그리드의 범위를 벗어났거나 셀의 값이 0인 경우 count를 1 증가시킨다.

count를 반환한다.



코드

class Solution {
    public int islandPerimeter(int[][] grid) {
        int[][] dir = {{-1,0}, {0,1}, {1,0}, {0,-1}};
        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) {
                    for (int k = 0; k < dir.length; k++) {
                        int newI = i + dir[k][0];
                        int newJ = j + dir[k][1];
                        if (newI < 0 || newI >= grid.length || newJ < 0 || newJ >= grid[0].length) {
                            count++;
                        } else {
                            if (grid[newI][newJ] == 0) {
                                count++;
                            }
                        }
                    }
                }
            }
        }
        return count;
    }
}
profile
차근차근 하나씩

0개의 댓글