5 August 2020
LeetCode(212) -- Word Search II
by Jerry Zhang
Problem
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example:
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"]
Solution
class Solution {
class TrieNode {
TrieNode[] children = new TrieNode[26];
String word = null;
}
char[][] _board = null;
ArrayList<String> _result = new ArrayList<String>();
public List<String> findWords(char[][] board, String[] words) {
TrieNode root = new TrieNode();
for (String word : words) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (node.children[c - 'a'] == null) {
node.children[c - 'a'] = new TrieNode();
}
node = node.children[c - 'a'];
}
node.word = word;
}
this._board = board;
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
if (root.children[board[row][col] - 'a'] != null) {
backtracking(row, col, root);
}
}
}
return this._result;
}
private void backtracking(int row, int col, TrieNode parent) {
char letter = this._board[row][col];
TrieNode currNode = parent.children[letter - 'a'];
if (currNode.word != null) {
this._result.add(currNode.word);
currNode.word = null;
}
this._board[row][col] = '#';
int[] rowOffset = {-1, 0, 1, 0};
int[] colOffset = {0, 1, 0, -1};
for (int i = 0; i < 4; ++i) {
int newRow = row + rowOffset[i];
int newCol = col + colOffset[i];
if (newRow < 0 || newRow >= this._board.length || newCol < 0
|| newCol >= this._board[0].length) {
continue;
}
char neighbor = this._board[newRow][newCol];
if (neighbor != '#' && currNode.children[neighbor - 'a'] != null) {
backtracking(newRow, newCol, currNode);
}
}
this._board[row][col] = letter;
}
}