일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 화상영어
- 프로젝트
- leetcode
- 30분
- 월간
- 쓰릴오브파이트
- Problem Solving
- FIT XR
- 영어원서읽기
- 사이드
- 스탭퍼
- 파비최
- 영어공부
- 링피트
- 매일
- 3줄정리
- 개발자
- English
- 읽기
- Daily Challenge
- Writing
- 운동
- 만화도
- 리얼 클래스
- 미드시청
- 괜찮음
- 뭐든
- 잡생각
- 10분
- realclass
Archives
- Today
- Total
파비의 매일매일 공부기록
2023.05.21 Today's Challenge 본문
https://leetcode.com/problems/shortest-bridge/
Shortest Bridge - LeetCode
Can you solve this real interview question? Shortest Bridge - You are given an n x n binary matrix grid where 1 represents land and 0 represents water. An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly
leetcode.com
BFS / DFS로 푸는 문제.
class Solution:
def shortestBridge(self, grid: List[List[int]]) -> int:
n = len(grid)
fx, fy = -1, -1
for i in range(n):
for j in range(n):
if grid[i][j] == 1:
fx, fy = i, j
break
def dfs(x, y):
grid[x][y] = 2
q.append((x,y))
for cx, cy in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]:
if 0 <= cx < n and 0 <= cy < n and grid[cx][cy] == 1:
dfs(cx, cy)
q = []
dfs(fx, fy)
d = 0
while q:
nb = []
for x, y in q:
for cx, cy in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)] :
if 0 <= cx < n and 0 <= cy < n:
if grid[cx][cy] == 1:
return d
elif grid[cx][cy] == 0:
nb.append((cx, cy))
grid[cx][cy] = -1
q = nb
d += 1
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
2023.05.23 Today's Challenge (0) | 2023.05.23 |
---|---|
2023.05.22 Today's Challenge (0) | 2023.05.22 |
2023.05.20 Today's Challenge (0) | 2023.05.20 |
2023.05.19 Today's Challenge (0) | 2023.05.19 |
2023.05.18 Today's Challenge (0) | 2023.05.18 |
Comments