파비의 매일매일 공부기록

2023.05.21 Today's Challenge 본문

Problem Solving/LeetCode

2023.05.21 Today's Challenge

fabichoi 2023. 5. 21. 23:45

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