[leetcode]212.word-search-ii

yoon·2023년 9월 11일
0

leet_code

목록 보기
21/24

📃문제 설명

input에는 board를 구성하는 문자가 주어지고, 내가 찾고 싶은 단어가 리스트 형태로 주어진다. 이때 찾고 싶은 단어를 보드에서 만들 수 있다면 그 단어를 return 값으로 준다.

🖊 풀이

from functools import reduce
from collections import defaultdict
class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        
        # create trie
        Trie = lambda: defaultdict(Trie)
        trie = Trie()
        END = True
        
        for word in words:
            reduce(dict.__getitem__,word,trie)[END] = word
        
        res = set()
        def findstr(i,j,t):
            if END in t:
                res.add(t[END])
                # return
            letter = board[i][j]
            board[i][j] = ""
            if i > 0 and board[i-1][j] in t:
                findstr(i-1,j,t[board[i-1][j]])
            if j>0 and board[i][j-1] in t:
                findstr(i,j-1,t[board[i][j-1]])
            if i < len(board)-1 and board[i+1][j] in t:
                findstr(i+1,j,t[board[i+1][j]])
            if j < len(board[0])-1 and board[i][j+1] in t:
                findstr(i,j+1,t[board[i][j+1]])
            board[i][j] = letter
            
            return 
        
        for i, row in enumerate(board):
            for j, char in enumerate(row):
                if board[i][j] in trie:
                    findstr(i,j,trie[board[i][j]])
        return res

dfs를 이용하여 접근해야 한다는 것은 이해했는데 접근법을 몰라서 찾아본 코드이다.
코드가 풀어서 작성되어 있어 이해하기 편해서 가져왔다.
재귀함수를 사용하여서 열과 행을 탐색하는 과정을 조금 쉽게 이해한 것 같다.

profile
하루하루 차근차근🌱

0개의 댓글