Search code examples
c++depth-first-search

Why is this solution giving TLE on the given test case?


Question link : https://leetcode.com/problems/word-search/

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighbouring. The same letter cell may not be used more than once.

We are not supposed to use one character twice.

Example :

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

Constraints :

board and word consists only of lowercase and uppercase English letters.
1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3

My Logic : In function exists, whenever I find the first character of the given string( string s ) in the 2D array I call DFS on its position, to check if the string can be formed.

I am getting TLE on the mentioned Test Case

Test Case :

[["a","a","a","a"],["a","a","a","a"],["a","a","a","a"],["a","a","a","a"],["a","a","a","b"]]
"aaaaaaaaaaaaaaaaaaaa"

Expected Output :

true

Code :

class Solution {
public:
    
    bool dfs( vector<vector<char>> board , string s, int p ,int i , int j ){

        if( p == s.length() ){
            return true;
        }
        
        if( i < 0 || i >= board.size() || j < 0 || j >= board[i].size() || board[i][j] != s.at(p) ){
            return false;
        }
        
        char t = board[i][j];
        board[i][j] = ' ';
        
        bool res = dfs( board, s, p + 1 , i + 1, j ) | dfs( board, s, p + 1 , i - 1, j ) |
            dfs( board, s, p + 1 , i , j + 1 ) | dfs( board, s, p + 1 , i, j - 1 );
        
        board[i][j] = t;
        
        return res;
        
    }
    
    bool exist(vector<vector<char>>& board, string s) {
        
        for( int i = 0; i < board.size(); i++ ){
            for( int j = 0; j < board[0].size(); j++ ){
                if( board[i][j] == s.at(0) && dfs( board , s , 0, i , j ) ){
                    return true;
                }
            }
        }
        return false;
    }
};

Submission Details : https://leetcode.com/submissions/detail/398643848/


Solution

  • Recursive function dfs receives board by value, i.e. it cannot change it while it apparently tries. Timeout due to huge amount of copies and infinite recursion. Looks like bug.