Problem
Intuition: Since we have to find words (on the grid/board) present in words array by traversing in up/down/left/right fashion.
The traversal can be done using backtracking
For searching of the word we can make use of trie, since this will also help us in early identification by checking if a prefix is present in the tree or not. This is avoid un-necessary traversal of the board(i.e. no point in traversing the board, if the prefix is not present in the trie, then string or word form using the prefix will also not be present in the trie)
Approach: We will put all the words[] in the trie, then we will traverse the board for each cell(i,j) and will go in all the 4 directions to form various strings, and we will put all the strings that are present in the trie in a list.
class Solution { public List<string> findWords(char[][] board, String[] words) { int max = 0; Trie t = new Trie(); for (String w : words) { t.insert(w); } int arr[][] = new int[board.length][board[0].length]; StringBuilder str = new StringBuilder(); Set<string> list = new HashSet();// to have only unique strings/words for (int i = 0; i (list); } public void traverse(int i, int j, char b[][], int arr[][], int n, int m, Trie t, StringBuilder str,Set<string> list) { str.append(b[i][j]);// add current cell character to form a potential prefix/word if (!t.startWith(str.toString())) {//early checking of prefix before moving forward to avoid un-necessary traversal str.deleteCharAt(str.length() - 1); return; } if (t.present(str.toString())) list.add(str.toString()); arr[i][j] = 1;// mark current cell visited to avoid visiting the same cell the current recursive call stack int dirs[][] = { { 0, -1 }, { 0, 1 }, { -1, 0 }, { 1, 0 } };// left,right,up,down for (int dir[] : dirs) { int I = i + dir[0]; int J = j + dir[1]; if (I = 0 && J >= 0 && arr[I][J] == 0) { traverse(I, J, b, arr, n, m, t, str, list); } } arr[i][j] =0;// mark unvisited str.deleteCharAt(str.length()-1);// remove the last added character } } class Node { Node node[] = new Node[26]; boolean flag; public boolean isPresent(char c) { return node[c - 'a'] != null; } public Node get(char c) { return node[c - 'a']; } public void add(char c, Node n) { node[c - 'a'] = n; } public void setFlag() { this.flag = true; } public boolean getFlag() { return this.flag; } } class Trie { Node root; public Trie() { root = new Node(); } public void insert(String s) { Node node = root; for (int i = 0; i </string></string></string>
The above is the detailed content of Word Search II. For more information, please follow other related articles on the PHP Chinese website!

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
