본문 바로가기

Algorithm/LeetCode24

[LeetCode] 1162 | As Far from Land as Possible 1162 | As Far from Land as Possible https://leetcode.com/problems/as-far-from-land-as-possible/ 작성 코드 접근 방법 0인 grid[x][y]에서 가장 가까운 1 값까지의 거리를 저장해서 max 값을 return import collections class Solution: def maxDistance(self, grid: List[List[int]]) -> int: counts = -1 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 0: q = collections.deque() q.append([i, j, 0, []]) while q: x, .. 2022. 4. 5.
[LeetCode] 1020 | Number of Enclaves 1020 | Number of Enclaves https://leetcode.com/problems/number-of-enclaves/ 작성 코드 접근 방법 boundary 경계에 있는 원소들에 접근하여 인접 요소들을 0(물)으로 변환함 남은 grid 중 1을 count class Solution: def numEnclaves(self, grid: List[List[int]]) -> int: def dfs_boundary(x, y): if x = len(grid) or y = len(grid[0]) or grid[x][y] == 0: return grid[x][y] = 0 dfs_boundary(x - 1, y) dfs_boundary(x + 1, y) dfs_boun.. 2022. 4. 4.
[LeetCode] 11 | Container With Most Water 11 | Container With Most Water https://leetcode.com/problems/container-with-most-water/ 작성 코드 class Solution: def maxArea(self, height: List[int]) -> int: water = 0 for j in range(len(height)): for k in range(j, len(height)): water = max(water, (k - j) * min(height[j], height[k])) return water 시간 초과 발생 이상 코드 class Solution: def maxArea(self, height: List[int]) -> int: start, end = 0, len(height).. 2022. 4. 1.
[LeetCode] 1905 | Count Sub Islands 1905 | Count Sub Islands https://leetcode.com/problems/count-sub-islands/ 작성 코드 class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: def dfs(x, y): if x = len(grid2) or y = len(grid2[0]) or grid2[x][y] == 0: return [] grid2[x][y] = 0 return [[x, y]] + dfs(x - 1, y) + dfs(x + 1, y) + dfs(x, y - 1) + dfs(x, y + 1) answer = 0 islands .. 2022. 3. 30.
[LeetCode] 1254 | Number of Closed Islands 1254 | Number of Closed Islands https://leetcode.com/problems/number-of-closed-islands/ 작성 코드 접근 방법 for 문을 돌며 grid[x][y] = 0 인 곳은 dfs 으로 상하좌우 탐색 후, 한 번 돌면 count += 1 모든 면이 물(1)로 둘러 쌓여야 하기 때문에, 테두리에 grid[x][y] = 0 인 곳은 dfs 상하좌우 탐색 하여 1로 변환해줌 class Solution: def closedIsland(self, grid: List[List[int]]) -> int: def dfs(x, y): if (x = len(grid) or y = len(grid[0])) or grid[x][y].. 2022. 3. 29.
[LeetCode] 6 | Zigzag Conversion 6 | Zigzag Conversion https://leetcode.com/problems/zigzag-conversion/ 작성 코드 접근 방법 각 행에 반복되는 규칙을 찾아 인덱스로 저장하자 class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s elif numRows == 2: indexes = [] indexes += [s[index] for index in range(0, len(s), 2)] indexes += [s[index] for index in range(1, len(s), 2)] return ''.join(indexes) indexes = [] repeat = numRows + .. 2022. 3. 21.
반응형