-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathword_search.cpp
More file actions
66 lines (61 loc) · 1.45 KB
/
word_search.cpp
File metadata and controls
66 lines (61 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Word Search - https://leetcode.com/problems/word-search/
#include <bits/stdc++.h>
using namespace std;
int n,m;
bool isvalid(int i, int j)
{
return (0<=i && i<n && 0<=j && j<m);
}
bool rec(vector<vector<char>>& board,string word,int idx,int i, int j,vector<vector<bool>> &vis)
{
if(idx==word.length())
return true;
if(!(isvalid(i,j) && !vis[i][j] && word[idx]==board[i][j]))
return false;
vis[i][j] = true;
bool f = false;
f |= rec(board,word,idx+1,i-1,j,vis);
if(f)
return true;
f |= rec(board,word,idx+1,i,j-1,vis);
if(f)
return true;
f |= rec(board,word,idx+1,i+1,j,vis);
if(f)
return true;
f |= rec(board,word,idx+1,i,j+1,vis);
if(f)
return true;
vis[i][j] = false;
return false;
}
bool exist(vector<vector<char>>& board, string word)
{
n = board.size();
m = board[0].size();
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
vector<vector<bool>> vis(n,vector<bool>(m,false));
if(rec(board,word,0,i,j,vis))
return true;
}
}
return false;
}
int main()
{
cin>>n>>m;
vector<vector<char>> board;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
cin>>board[i][j];
string word;
cin>>word;
if(exist(board,word))
cout<<"Given word exists in the board\n";
else
cout<<"Given word does not exist in the board\n";
return 0;
}