https://leetcode.com/problems/word-search-ii/description/
Word Search II - LeetCode
Can you solve this real interview question? Word Search II - 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
leetcode.com
보드의 문자열을 순회하며 단어를 만들 수 있는지 확인하는 문제이다.
보드의 문자를 순차적으로 연결하는 문제이기에 초기에 백트래킹을 이용하여 해결하려고 시도했다.
하지만 찾아야 하는 단어가 배열로 많이 주어지고,같은 prefix를 갖는 단어들이 주어지는 테스트 케이스가 존재하여 시간 초과가 되었다. 이를 해결하기 위해 Trie 자료구조를 이용했다. 아래는 완성한 통과 코드이다.
import java.util.*;
public class Solution {
Set<String> answerSet;
char[][] board;
boolean[][] visited;
int[] dr = {-1, 0, 1, 0};
int[] dc = {0, -1, 0, 1};
int m;
int n;
public List<String> findWords(char[][] board, String[] words) {
this.board = board;
this.m = board.length;
this.n = board[0].length;
this.visited = new boolean[m][n];
TrieNode root = new TrieNode();
answerSet = new HashSet<>();
for(String word: words){
TrieNode head = root;
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
int check = c - 'a';
if(head.next[check] == null){
head.next[check] = new TrieNode();
}
TrieNode next = head.next[check];
head = next;
if(i == word.length() - 1){
head.isLast = true;
}
}
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
visited[i][j] = true;
sb.append(board[i][j]);
findWord(root, i, j, sb);
visited[i][j] = false;
sb.setLength(sb.length() - 1);
}
}
return new ArrayList<>(answerSet);
}
private void findWord(TrieNode head, int r, int c, StringBuilder sb){
char ch = board[r][c];
int check = ch - 'a';
if(head.next[check] == null){
return;
}
head = head.next[check];
if(head.isLast){
answerSet.add(sb.toString());
}
for(int k = 0; k < dr.length; k++){
int nextRow = r + dr[k];
int nextCol = c + dc[k];
if(nextRow >= 0 && nextRow < m
&& nextCol >= 0 && nextCol < n
&& !visited[nextRow][nextCol]){
visited[nextRow][nextCol] = true;
sb.append(board[nextRow][nextCol]);
findWord(head, nextRow, nextCol, sb);
visited[nextRow][nextCol] = false;
sb.deleteCharAt(sb.length() - 1);
}
}
}
private static class TrieNode{
TrieNode[] next;
boolean isLast;
TrieNode(){
next = new TrieNode[26];
isLast = false;
}
}
}
중복되는 정답을 정리하기 위해 Set을 이용해주었다. 해결한 이후 보다 빠른 통과 코드를 확인해보았다. 다른 점은 TrieNode에 isLast 대신 String word를 넣어주는 방법이었다. word를 저장시 isLast 지점에서 word 자체를 저장하는 방식이었다.
private static class TrieNode{
TrieNode[] next;
String word;
TrieNode(){
next = new TrieNode[26];
}
}
}
해당 클래스에 word를 넣어주면 백트래킹 탐색시 문자열 검색이 쉬워지는 장점이 있다. 또한 Set을 이용할 필요 없이 word를 지워주는 방식으로 중복을 제거할 수 있었다. Trie 구조가 익숙하지 않았었기에 새로운 사용 방식을 배울 수 있었다.
'Algolithm-Leetcode > Trie' 카테고리의 다른 글
| Replace Words (0) | 2026.08.26 |
|---|---|
| Longest Common Prefix (0) | 2026.08.22 |
| Design Add and Search Words Data Structure (0) | 2026.08.12 |
| Implement Trie (Prefix Tree) (0) | 2026.08.10 |