Here is a problem from Leetcode: Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
I did simple backtracking with dfs, here is my code:
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int index = 0;
for(int i = 0; i < board.size(); i++) {
for(int j = 0; j < board[0].size(); j++) {
if(existsUtil(board, index, word, i, j))
return true;
}
}
return false;
}
bool existsUtil(vector<vector<char>> board, int index, string word, int i, int j) {
if(index >= word.length())
return true;
if(i < 0 || i >= board.size() || j < 0 || j >= board[0].size() || board[i][j] != word[index] || board[i][j] == '0')
return false;
char temp = board[i][j];
board[i][j] = '0';
index += 1;
bool value = existsUtil(board, index, word, i + 1, j) || existsUtil(board, index, word, i, j - 1) || existsUtil(board, index, word, i - 1, j) || existsUtil(board, index, word, i, j + 1);
board[i][j] = temp;
return value;
}
};
This code is giving TLE for larger inputs. But in the dfs function, if I pass the board
parameter by referece, that is, if I pass vector<vector<char>> &board
, it passes all test cases. Why is this happening?