Introduction
Searching for a word inside a 2D character matrix is a common matrix and grid-based interview problem. The challenge becomes more interesting when the word can be formed in any of the 8 directions, including horizontal, vertical, and diagonal directions.
In this article, we will solve the Word in Grid – All Occurrences problem in Java and understand the directional traversal technique, why DFS is not required, and how to achieve the expected time and space complexity.
Problem Statement
Given a 2D character matrix mat[][] and a string word, find all starting positions where the given word occurs in the matrix.
The word can be formed by moving in any of the 8 directions:
Left
Right
Up
Down
Top-left diagonal
Top-right diagonal
Bottom-left diagonal
Bottom-right diagonal
The movement must remain in the same direction throughout an occurrence.
Each cell can be used at most once for an occurrence, and the result should contain unique starting coordinates in lexicographically smallest order.
Example
Consider the following matrix:
a b a b
a b e b
e b e b
and:
word = "abe"
The word can be found starting at:
(0,0)
(0,2)
(1,0)
Therefore, the expected output is:
[[0,0], [0,2], [1,0]]
For example, starting from (0,0), the word is found diagonally:
(0,0) → a
(1,1) → b
(2,2) → e
Key Observation
The most important observation is that the word must be formed in a straight line.
Once we choose a direction, we do not change direction while matching the remaining characters.
There are exactly eight possible directions:
↖ ↑ ↗
← →
↙ ↓ ↘
Instead of writing separate logic for each direction, we can represent the row and column movement using two arrays:
int[] dr = {-1, -1, -1, 0, 0, 1, 1, 1};
int[] dc = {-1, 0, 1, -1, 1, -1, 0, 1};
Here:
drrepresents the change in the row.dcrepresents the change in the column.
For example:
dr = -1
dc = 0
means move one row upward.
Similarly:
dr = 1
dc = 1
means move diagonally down-right.
Approach
We can solve the problem using the following steps.
Step 1: Traverse Every Cell
Use two nested loops to consider every matrix cell as a potential starting position.
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// Check this cell
}
}
Step 2: Check the First Character
There is no reason to search from a cell if it does not contain the first character of the word.
if (mat[i][j] != word.charAt(0)) {
continue;
}
For example, if:
word = "abe"
we only need to start searching from cells containing a.
Step 3: Try All Eight Directions
For every valid starting cell, check all eight possible directions.
for (int d = 0; d < 8; d++) {
// Check this direction
}
The variable d represents the current direction.
Step 4: Move Through the Matrix
Initially, the current position is the starting cell:
int r = i;
int c = j;
For every subsequent character, move using the selected direction:
r += dr[d];
c += dc[d];
Because the same d is used for every step, the search continues in a straight line.
Step 5: Check the Boundaries
Before accessing the matrix, verify that the position is inside the grid:
if (r < 0 || r >= n || c < 0 || c >= m) {
break;
}
This prevents an ArrayIndexOutOfBoundsException.
Step 6: Compare Characters
The character at the current matrix position must match the corresponding character in the word.
if (mat[r][c] != word.charAt(k)) {
break;
}
If the character does not match, that direction cannot form the word.
Step 7: Store the Starting Position
If all characters have been matched, the word has been found.
The required result is the starting coordinate, so we store (i, j):
ArrayList<Integer> position = new ArrayList<>();
position.add(i);
position.add(j);
result.add(position);
Complete Java Solution
import java.util.ArrayList;
class Solution {
public ArrayList<ArrayList<Integer>> searchWord(
char[][] mat, String word) {
ArrayList<ArrayList<Integer>> result =
new ArrayList<>();
int n = mat.length;
int m = mat[0].length;
// 8 possible directions
int[] dr = {-1, -1, -1, 0, 0, 1, 1, 1};
int[] dc = {-1, 0, 1, -1, 1, -1, 0, 1};
// Traverse every cell
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// First character must match
if (mat[i][j] != word.charAt(0)) {
continue;
}
// Try all 8 directions
for (int d = 0; d < 8; d++) {
int r = i;
int c = j;
int k;
// Check remaining characters
for (k = 1; k < word.length(); k++) {
r += dr[d];
c += dc[d];
// Check boundary
if (r < 0 || r >= n || c < 0 || c >= m) {
break;
}
// Character mismatch
if (mat[r][c] != word.charAt(k)) {
break;
}
}
// Complete word found
if (k == word.length()) {
ArrayList<Integer> position =
new ArrayList<>();
position.add(i);
position.add(j);
result.add(position);
// Avoid duplicate starting position
break;
}
}
}
}
return result;
}
}
Understanding the Direction Arrays
The following arrays are the heart of the solution:
int[] dr = {-1, -1, -1, 0, 0, 1, 1, 1};
int[] dc = {-1, 0, 1, -1, 1, -1, 0, 1};
They represent the eight possible movements:

Join the conversation! Your thoughts help the community grow.