Count of number of given string in 2D character array

Pattern: Word search

medium

The same search as Word Search, but instead of stopping at the first match, add up the matches from all four directions at every step and from every starting cell.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given a grid of letters and a word, count the number of distinct paths that spell the word, moving up, down, left or right between cells and never using a cell twice on one path. Different starting cells or different routes count separately. For example, the 6 × 6 grid in the GeeksforGeeks example gives 3 for MAGIC, and the grid AB / BA gives 4 for AB.

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name countWord and this exact counting rule are this guide's own.

Think first

  • How is "count" different from "exists" in the recursion?
  • When does one path count as one?
  • Is each path counted once, even if it could be reached by different orders of exploration?

Hints

    Brute force, and why it fails

    This is the exhaustive search already; with counting, every matching path must be visited. The letter check prunes all other paths at once.

    The key insight

    Each path is built by exactly one sequence of choices in the recursion, so adding the branch counts counts every path exactly once.

    Dry run

    A B0 
    B A1 

    The grid rows are AB and BA, and the word is AB.

    Step 1 of 4

    The plan

    function count(r, c, i):
        if (r, c) is outside or grid[r][c] != word[i]: return 0
        if i == len(word) - 1: return 1
        saved = grid[r][c]; grid[r][c] = '#'
        ways = sum of count on the four neighbours with i + 1
        grid[r][c] = saved
        return ways
    return sum of count(r, c, 0) over all cells
    

    Complexity

    Time
    O(R × C × 3^L)
    Space
    O(L)

    As Word Search, but without the early stop. The recursion is L deep.

    Edge cases

    • A one-letter word: the number of cells holding it.
    • No match: 0.
    • Palindromic words count the same cells in both directions as different paths.
    I've built my logic, show the code

    Java

    class Solution {
        public int countWord(char[][] grid, String word) {
            int total = 0;
            for (int r = 0; r < grid.length; r++)
                for (int c = 0; c < grid[0].length; c++)
                    total += count(grid, word, r, c, 0);    // paths starting at every cell
            return total;
        }
    
        private int count(char[][] g, String w, int r, int c, int i) {
            if (r < 0 || c < 0 || r >= g.length || c >= g[0].length || g[r][c] != w.charAt(i)) return 0;
            if (i == w.length() - 1) return 1;              // one complete path
            char saved = g[r][c];
            g[r][c] = '#';                                  // not reusable on this path
            int ways = count(g, w, r + 1, c, i + 1) + count(g, w, r - 1, c, i + 1)
                     + count(g, w, r, c + 1, i + 1) + count(g, w, r, c - 1, i + 1);
            g[r][c] = saved;
            return ways;
        }
    }

    C++

    class Solution {
    public:
        int countWord(vector<vector<char>>& grid, string word) {
            int total = 0;
            for (size_t r = 0; r < grid.size(); r++)
                for (size_t c = 0; c < grid[0].size(); c++)
                    total += count(grid, word, static_cast<int>(r), static_cast<int>(c), 0);   // every starting cell
            return total;
        }
    
        int count(vector<vector<char>>& g, const string& w, int r, int c, size_t i) {
            if (r < 0 || c < 0 || r >= static_cast<int>(g.size()) || c >= static_cast<int>(g[0].size()) || g[r][c] != w[i]) return 0;
            if (i == w.size() - 1) return 1;                // one complete path
            char saved = g[r][c];
            g[r][c] = '#';                                  // not reusable on this path
            int ways = count(g, w, r + 1, c, i + 1) + count(g, w, r - 1, c, i + 1)
                     + count(g, w, r, c + 1, i + 1) + count(g, w, r, c - 1, i + 1);
            g[r][c] = saved;
            return ways;
        }
    };

    Python

    class Solution:
        def countWord(self, grid: list[list[str]], word: str) -> int:
            R, C = len(grid), len(grid[0])
    
            def count(r: int, c: int, i: int) -> int:
                if not (0 <= r < R and 0 <= c < C) or grid[r][c] != word[i]:
                    return 0
                if i == len(word) - 1:
                    return 1                        # one complete path
                saved, grid[r][c] = grid[r][c], "#" # not reusable on this path
                ways = count(r + 1, c, i + 1) + count(r - 1, c, i + 1) + count(r, c + 1, i + 1) + count(r, c - 1, i + 1)
                grid[r][c] = saved
                return ways
    
            return sum(count(r, c, 0) for r in range(R) for c in range(C))

    Common mistakes

    • Stopping at the first match.
    • Forgetting to restore cells, which undercounts later paths.
    • Counting cells instead of paths.

    Similar problems