엔지니어 게시판
LeetCode 솔루션 분류

[11/5] 212. Word Search II

컨텐츠 정보

본문

Hard
7661347Add to ListShare

Given an m x n board of characters and a list of strings words, return all words on the board.

Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

 

Example 1:

Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]

Example 2:

Input: board = [["a","b"],["c","d"]], words = ["abcb"]
Output: []

 

Constraints:

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 12
  • board[i][j] is a lowercase English letter.
  • 1 <= words.length <= 3 * 104
  • 1 <= words[i].length <= 10
  • words[i] consists of lowercase English letters.
  • All the strings of words are unique.
Accepted
512,675
Submissions
1,388,063

관련자료

댓글 1

학부유학생님의 댓글

  • 익명
  • 작성일
class TrieNode:
    def __init__(self):
        self.word = None
        self.children = {}
        
class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        trieroot = TrieNode()
        
        for word in words:
            node = trieroot
            
            for idx, char in enumerate(word):
                if char not in node.children:
                    node.children[char] = TrieNode()
                node = node.children[char]
                if idx == len(word)-1:
                    node.word = word
        
        directions = [(1,0), (0,1), (-1,0), (0,-1)]
        
        ROW, COL = len(board), len(board[0])
        path = set()
        
        res = []
        
        def dfs(row, col, trienode):
            if trienode.word:
                res.append(trienode.word)
                trienode.word = None
            path.add((row,col))
            
            for rd, cd in directions:
                nr, nc = row+rd, col+cd
                if 0<=nr<ROW and 0<=nc<COL and (nr,nc) not in path and board[nr][nc] in trienode.children:
                    dfs(nr,nc,trienode.children[board[nr][nc]])
            
            path.remove((row,col))
        
        for r in range(ROW):
            for c in range(COL):
                if board[r][c] in trieroot.children:
                    node = trieroot
                    dfs(r,c,node.children[board[r][c]])
        return res
전체 404 / 1 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 769 명
  • 오늘 방문자 6,624 명
  • 어제 방문자 6,975 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,537 명
알림 0