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.
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"]
Input: board = [["a","b"],["c","d"]], words = ["abcb"]
Output: []
m == board.lengthn == board[i].length1 <= m, n <= 12board[i][j] is a lowercase English letter.1 <= words.length <= 3 * 1041 <= words[i].length <= 10words[i] consists of lowercase English letters.words are unique.In the brute force approach, we iterate over each word and place it character by character on the board, starting from every potential starting point. This involves a depth-first search (DFS) from each cell for each word and checking all four possible directions. This naive method helps understand the base working but lacks efficiency.
To optimize, we use a Trie data structure for efficient prefix checking. Trie allows us to minimize unnecessary DFS calls by terminating branches early if a prefix leads to no valid word. For each starting point on the board, we search using the trie to construct words, reducing redundant operations considerably compared to checking each word independently.