leetcode
-
[LeetCode] 695. Max Area of Island알고리즘 2022. 5. 28. 22:47
[LeetCode] Max Area of Island 이 문제는 dfs 를 활용해서 풀 수 있는 문제이다. dfs 는 depth first search 의 약자로서, 그래프 탐색 알고리즘의 한 종류이다. 이름에서 알 수 있듯이 노드에서 연결된 노드가 있으면 계속 연결된 부분을 통해 이동하면서 그래프를 탐색한다. dfs 는 운이 좋을 경우 해를 빠르게 구할 수 있지만, 항상 최적의 해를 보장하지는 않는다. 또한 dfs 는 스택 자료구조를 사용하며 구현할 수 있다. (재귀의 동작이 스택과 똑같음) 해가 없는 경로에 깊게 빠질 수 있다. 따라서 예외처리를 잘 해주어야한다. class Solution: def maxAreaOfIsland(self, grid: List[List[int]]) -> int: n = ..
-
[LeetCode] 773. Flood Fill알고리즘 2022. 5. 26. 23:23
[LeetCode] 773. Flood Fill DFS 로 풀 수 있는 문제이다. 나의 풀이 class Solution: def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: n = len(image) m = len(image[0]) visited = [[0] * m for _ in range(n)]; dx = [1,-1,0,0] dy = [0,0,1,-1] def dfs(r,c, targetColor, newColor): for _ in range(4): newR = r + dy[_] newC = c + dx[_] if (newR = n or newC < 0 o..
-
[LeetCode] 1342. Number of Steps to Reduce a Number to Zero알고리즘 2022. 4. 23. 23:57
[LeetCode] 1342. Number of Steps to Reduce a Number to Zero 풀이_#1 if 문을 이용한 간단한 풀이 class Solution(object): def numberOfSteps(self, num): """ :type num: int :rtype: int """ r = 0 while (num): if (num % 2): num = num - 1 else: num /= 2 r += 1 return r비트를 이용한 풀이 Long answer The two operations in the problem are divide the number by 2 when even, or subtract 1 from the number when odd. In binary form..