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 algorithm problems with animated visualisers that show the data structure changing as the code runs.

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(NM8L)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(NM)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))

Related reading
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
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.