[PS] Leet | 212. 단어 찾기 II

2025. 7. 25. 16:55·CS/PS

문제

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: []

조건

  • 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.

답

단어찾기I 과 같이 각 위치마다 단어검사를 시행하면 O(n^3)의 시간 복잡도를 가지기 때문에 효율이 좋지 못합니다.

 

찾고자 하는 단어들을 Trie 자료 구조로 저장한 뒤,

 

각 위치마다 DFS를 시행하면서 Trie의 자료구조를 읽어나가면 O(n^2)의 시간 복잡도로 해결할 수 있습니다.

/**
 * @param {character[][]} board
 * @param {string[]} words
 * @return {string[]}
 */
var findWords = function(board, words) {
    const m = board.length;
    const n = board[0].length;
    const res = [];
    const trie = {data: null};

    // DFS
    const search = (i, j, node) => {
        if (i < 0 || i >= m || j < 0 || j >= n) return
        const char = board[i][j];

        if (char in node){
            const suc = node[char];
            if (suc['data']){
                res.push(suc['data']);
                suc['data'] = null;
            }
            
            board[i][j] = '#'
            search(i+1, j, suc);
            search(i-1, j, suc);
            search(i, j+1, suc);
            search(i, j-1, suc);
            board[i][j] = char;
        }
    }
    
    // Trie 자료구조 초기화
    for (const word of words) {
        let node = trie;
        for (const char of word) {
            if (!(char in node)) node[char] = {data: null};
            node = node[char];
        }
        node['data'] = word;
    }
    
    // 각 위치마다 DFS를 시행하면서 Trie와 값 비교
    for (let i=0; i<m; ++i) {
        for (let j=0; j<n; ++j) {
            search(i, j, trie);
        }
    }

    return res
};
728x90

'CS > PS' 카테고리의 다른 글

[PS] Leet | 146. LRU 캐시  (1) 2025.08.18
[PS] Leet | 295. 데이터 스트림에서 중간값 찾기  (2) 2025.08.06
[PS] Leet | 211. 단어 데이터 추가 및 탐색  (0) 2025.07.22
[PS] Leet | 105. Preorder와 Inorder 수열로부터 트리 구성하기  (0) 2025.07.09
[PS] Leet | 5. 가장 긴 팰린드롬 하위문자열  (0) 2025.06.27
'CS/PS' 카테고리의 다른 글
  • [PS] Leet | 146. LRU 캐시
  • [PS] Leet | 295. 데이터 스트림에서 중간값 찾기
  • [PS] Leet | 211. 단어 데이터 추가 및 탐색
  • [PS] Leet | 105. Preorder와 Inorder 수열로부터 트리 구성하기
Rayi
Rayi
  • Rayi
    아카이브
    Rayi
  • 전체
    오늘
    어제
    • 분류 전체보기 (262)
      • CS (40)
        • ML (3)
        • CV (2)
        • PS (34)
      • Reveiw (17)
        • Paper (17)
        • Github (0)
      • Pytorch (5)
      • Language (58)
        • Python (7)
        • JavaScript (32)
        • TypeScript (16)
        • C++ (3)
      • IDE (12)
      • Git (13)
      • Frontend (71)
        • React (8)
        • SolidJS (20)
        • CSS (12)
      • UI (3)
      • Backend (15)
        • DB (17)
        • Node.js (11)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    html
    ps
    review
    figma
    CSS
    js
    UI
    CV
    deploy
    PyTorch
    DB
    SOLID
    Three
    GAN
    nodejs
    react
    python
    ts
    C++
    postgresql
    ML
    Git
    backend
    mongo
    CS
    PRISMA
    API
    frontend
    Express
    vscode
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
Rayi
[PS] Leet | 212. 단어 찾기 II
상단으로

티스토리툴바