Skip to content

-00f2134567890-=-=01Create 07_wordSearch.cpp #152

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions 10 October LeetCode Challenge 2021/07_wordSearch.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class Solution {
public:
bool exist(vector<vector<char>> &board, string word) {
// checking for all positions
for(int i = 0 ; i < board.size() ; ++i)
for(int j = 0 ; j < board[0].size() ; ++j)
if(dfs(0 , i , j , board , word))
return true;
return false;
}
bool dfs(int index , int x , int y , vector<vector<char>> &board , string &word)
{
if(index == word.size()) // word exists in matrix
return true;

if(x < 0 or y < 0 or x >= board.size() or y >= board[0].size() or board[x][y] == '.') // boundary check + visited check
return false;

if(board[x][y] != word[index])
return false;

char temp = board[x][y];
board[x][y] = '.'; // marking it visited

// Move in 4 directions[UP , DOWN , LEFT , RIGHT]
if(dfs(index + 1 , x - 1 , y , board , word) or dfs(index + 1 , x + 1 , y , board , word) or dfs(index + 1 , x , y - 1 , board , word) or dfs(index + 1 , x , y + 1 , board , word))
return true;

board[x][y] = temp; // backtrack step
return false;

}

};