Algorithm
2D Array
Word Search
Programming
Data Structures

Printing all possible words from a 2D array of characters

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

Exploring all possible words from a 2D character array is a classic problem that merges concepts from computer science and linguistic processing. This problem has applications in word games like Boggle and is fundamental to algorithms used in search engines and Natural Language Processing (NLP). In this article, we delve into the technicalities of generating words from a 2D grid of characters, providing explanations and examples along the way.

Problem Definition

Given a 2D grid (matrix) of characters, the task is to find all possible words that can be formed by tracing a path through adjacent characters in the grid. The constraints for path movement typically include:

  • You can move horizontally, vertically, or diagonally to adjacent cells.
  • A cell cannot be used more than once in a single word.
  • Words must be present in a given dictionary to be considered valid.

Algorithm Approach

The most common approach to solving this problem is the Depth-First Search (DFS) algorithm combined with backtracking. Here's a step-by-step breakdown:

  1. DFS Traversal: Start at each cell in the grid, attempting to form strings of various lengths by moving to adjacent cells using the DFS technique.
  2. Backtracking: Ensure that each cell is only visited once per word by marking cells as "visited."
  3. Dictionary Verification: During the DFS traversal, verify if the current string is a valid word by checking against a dictionary.

Pseudocode

  • Time Complexity: The worst-case scenario requires visiting each cell for a depth of L (the average length of a word or the maximum search depth), resulting in a time complexity of O(N⋅M⋅8L)O(N \cdot M \cdot 8^L), where N is the number of rows and M is the number of columns.
  • Space Complexity: Requires additional space for the visited array and call stack for DFS, typically O(N⋅M)O(N \cdot M).
  • "AB" (starting at (0,0) and moving to (0,1))
  • "BE" (starting at (0,1) and moving to (1,1))
  • "DEH" (starting at (1,0) and moving to (2,1))

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms