-
[LeetCode] 463. Island Perimeter c++Coding Test/LeetCode 2022. 12. 22. 12:56728x90
- 문제
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.
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.
바깥 단면의 개수를 구하는 문제이다.
- 문제 해결
A : 해당 사각형의 단면의 개수 = 4개
S : 겹치는 면의 개수
총 바깥 단면의 개수 : A - S
: (4*7) - 12 = 16
class Solution { public: int islandPerimeter(vector<vector<int>>& grid) { int row = grid.size(); int column = grid[0].size(); int result = 0; for(int i = 0; i < row; i++){ for(int j = 0; j < column; j++){ if(grid[i][j] == 1){ result += 4; if( i + 1 < row && grid[i+1][j] == 1){ result--; } if( i - 1 >= 0 && grid[i-1][j] == 1){ result--; } if( j + 1 < column && grid[i][j+1] == 1){ result--; } if( j - 1 >= 0 && grid[i][j-1] == 1){ result--; } } } } return result; } };
728x90'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 872. Leaf-Similar Trees c++ (0) 2022.12.22 [LeetCode] 965. Univalued Binary Tree c++ (0) 2022.12.22 [LeetCode] 559. Maximum Depth of N-ary Tree c++ (0) 2022.12.20 [LeetCode] 637. Average of Levels in Binary Tree c++ (0) 2022.12.20 [LeetCode] 104. Maximum Depth of Binary Tree c++ (1) 2022.12.20