Word Search II

This page explains Java solution to problem Word Search II using Trie data structure.

Problem Statement

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 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"]

Solution

If you have any suggestions in below code, please create a pull request by clicking here.

package com.vc.hard;

import java.util.*;

class WordSearchIi {
    class Node {
        String word;
        HashMap<Character, Node> map;

        Node() {
            map = new HashMap<>();
        }
    }

    class Trie {
        Node root = new Node();
        public void addWord(String str) {
            Node current = root;
            for(int i = 0; i < str.length(); i++) {
                char ch = str.charAt(i);
                if(!current.map.containsKey(ch)) current.map.put(ch, new Node());
                current = current.map.get(ch);
            }
            current.word = str;
        }
    }

    public List<String> findWords(char[][] board, String[] words) {

        HashSet<String> res = new HashSet<>();

        Trie trie = new Trie();
        for(String word: words) trie.addWord(word);

        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[0].length; j++) {
                if(trie.root.map.containsKey(board[i][j]))
                    solve(i, j, board, trie.root, res);
            }
        }

        return new ArrayList<>(res);
    }

    private int[][] dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
    private void solve(int row, int col, char[][] board, Node node, HashSet<String> res) {
        Node nodeNew = node.map.get(board[row][col]);

        if(nodeNew.word != null) {
            res.add(nodeNew.word);
        }

        char ch = board[row][col];
        board[row][col] = '#';

        for(int[] dir: dirs) {
            int rowNew = row + dir[0];
            int colNew = col + dir[1];
            if(rowNew >= 0 && rowNew < board.length && colNew >= 0 && colNew < board[0].length) {
                if(nodeNew.map.containsKey(board[rowNew][colNew]))
                    solve(rowNew, colNew, board, nodeNew, res);
            }
        }

        board[row][col] = ch;
    }
}

Time Complexity

O(M * 4 L) Where
M is total number of cells in an input board.
L is length of word which has a max Length in an input array words.

Space Complexity

O(N) Where
N is total number of words in a dictionary.