본문 바로가기
Algorithm/LeetCode

💯 Daily LeetCode Challenge Day_07 - Island Perimeter

by HaningYa 2020. 7. 7.
728x90

 

Account Login - LeetCode

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 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.

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:


오호우 격자 문줴에에쓰

이거 나오면 격자 bound 에 각각 1씩 추가해서 푸는거 몬지알쥐

예를들어
[0,1,0,0],
[1,1,1,0],
[0,1,0,0]
[1,1,0,0]
라면

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

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

요런 느낌스

간단하게 풀었스

class Solution {
    func islandPerimeter(_ grid: [[Int]]) -> Int {
        var answer = 0
        var map : [[Int]] = grid

        for i in 0..<map.count{
            map[i].insert(0 ,at:0)
            map[i].append(0)
        }
        map.insert(Array(repeating: 0, count: map[0].count), at:0)
        map.append(Array(repeating: 0, count: map[0].count))
//         [0, 0, 0, 0, 0, 0], 
//         [0, 0, 1, 0, 0, 0], 
//         [0, 1, 1, 1, 0, 0], 
//         [0, 0, 1, 0, 0, 0], 
//         [0, 1, 1, 0, 0, 0], 
//         [0, 0, 0, 0, 0, 0]
        // print(map)
        for i in 1..<map.count-1 {
            for j in 1..<map[i].count-1 {
                let current = map[i][j]
                if current == 1 {
                    //check up
                    if map[i+1][j] == 0 || map[i+1][j] == 2 && map[i+1][j] != 1{
                        answer += 1
                        map[i+1][j] = 2
                    }
                    //check down
                    if  map[i-1][j] == 0 || map[i-1][j] == 2 && map[i-1][j] != 1{
                        answer += 1
                        map[i-1][j] = 2
                    }
                    //check left
                    if map[i][j-1] == 0 || map[i][j-1] == 2 && map[i][j-1] != 1{
                        answer += 1
                        map[i][j-1] = 2
                    }
                    //check right
                    if map[i][j+1] == 0 || map[i][j+1] == 2 && map[i][j+1] != 1{
                        answer += 1
                        map[i][j+1] = 2
                    }
                }
            }
        }
        print(map)
        return answer
    }
}

 

근데 실행시간이

너무 느려서 어째 줄일까,,,

오후 쉣 print 문을 넣고 돌렸쓰

바로 주석처리 //빼애앰

만족s

여기까쥐스

728x90

댓글