LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제
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:
!https://assets.leetcode.com/uploads/2018/10/12/island.png
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.
- There is exactly one island in grid.
풀이
나의 풀이법
풀이 접근 과정
그냥 조건 다 걸어주고 계산했다.
최종 소스코드
class Solution {
fun islandPerimeter(grid: Array<IntArray>): Int {
var answer = 0
grid.forEachIndexed { i, arr ->
arr.forEachIndexed { j, it ->
if (it == 1) {
if (i == 0 ) answer++
if (i == grid.size-1) answer++
if (i > 0 && grid[i-1][j] == 0) answer++
if (i < grid.size-1 && grid[i+1][j] == 0) answer++
if (j == 0) answer++
if (j == arr.size-1) answer++
if (j > 0 && grid[i][j-1] == 0) answer++
if (j < grid[0].size-1 && grid[i][j+1] == 0) answer++
}
}
}
return answer
}
}
만약 제일 앞이면 +1 . 제일 뒤면 +1
사방을 비교해서 확인한 후 면 추가
모든 조건 계산
다른 풀이법
fun islandPerimeter(grid: Array<IntArray>): Int {
val rows = grid.size
val cols = grid[0].size
var perimeter = 0
for (row in 0 until rows) {
for (col in 0 until cols) {
if (grid[row][col] == 1) {
perimeter += 4 // 섬의 둘레를 4로 시작
// 상하좌우에 인접한 땅이 있으면 둘레를 줄임
if (row > 0 && grid[row - 1][col] == 1) {
perimeter -= 2
}
if (col > 0 && grid[row][col - 1] == 1) {
perimeter -= 2
}
}
}
}
return perimeter
}
둘레의 면을 다 잡아준 다음에 인접한 땅이 잇을 경우 둘레를 줄이는 방법.
오히려 내 풀이보다 간단한 듯
Comment
좀 더 깔끔하게 만들고 싶었는데 그러지 못해서 아쉽다
'LeetCode > Kotlin | Easy' 카테고리의 다른 글
[LeetCode/Kotlin]Easy - 228. Summary Ranges (0) | 2023.09.19 |
---|---|
[LeetCode/Kotlin]Easy - 704. Binary Search (0) | 2023.09.19 |
[LeetCode/Kotlin]Easy - 345. Reverse Vowels of a String (0) | 2023.09.14 |
[LeetCode/Kotlin]Easy - 441. Arranging Coins (0) | 2023.09.14 |
[LeetCode/Kotlin]Easy - 141. Linked List Cycle (0) | 2023.08.27 |