일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 | 31 |
Tags
- English
- 매일
- Problem Solving
- 잡생각
- realclass
- 영어원서읽기
- 10분
- 개발자
- Writing
- 괜찮음
- 사이드
- FIT XR
- 영어공부
- 만화도
- 화상영어
- leetcode
- 쓰릴오브파이트
- 월간
- Daily Challenge
- 30분
- 미드시청
- 파비최
- 운동
- 읽기
- 리얼 클래스
- 스탭퍼
- 뭐든
- 3줄정리
- 프로젝트
- 링피트
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