|
| 1 | +bool check(char graph[][MAXN],int n,int m,bool visited[][MAXN],string s,int i,int j) |
| 2 | +{ |
| 3 | + if(s[0]=='\0') |
| 4 | + return true; |
| 5 | + if(visited[i][j]==true) |
| 6 | + return false; |
| 7 | + visited[i][j]=true; |
| 8 | + bool ans=false; |
| 9 | + if(graph[i-1][j-1]==s[0]&&(i-1>=0&&j-1>=0)) |
| 10 | + { |
| 11 | + ans=check(graph,n,m,visited,s.substr(1),i-1,j-1); |
| 12 | + if(ans) |
| 13 | + return true; |
| 14 | + } |
| 15 | + if(graph[i-1][j]==s[0]&&i-1>=0) |
| 16 | + { ans=check(graph,n,m,visited,s.substr(1),i-1,j); |
| 17 | + if(ans) |
| 18 | + return true; |
| 19 | + } |
| 20 | + if(graph[i-1][j+1]==s[0]&&(i-1>=0&&j+1<m)) |
| 21 | + { ans = check(graph,n,m,visited,s.substr(1),i-1,j+1); |
| 22 | + if(ans) |
| 23 | + return true; |
| 24 | + } |
| 25 | + if(graph[i][j+1]==s[0] && j+1<m) |
| 26 | + { ans = check(graph,n,m,visited,s.substr(1),i,j+1); |
| 27 | + if(ans) |
| 28 | + return true; |
| 29 | + } |
| 30 | + if(graph[i+1][j+1]==s[0] && (j+1<m&&i+1<n)) |
| 31 | + { |
| 32 | + ans = check(graph,n,m,visited,s.substr(1),i+1,j+1); |
| 33 | + if(ans) |
| 34 | + return true; |
| 35 | + } |
| 36 | + if(graph[i+1][j]==s[0] && i+1<n) |
| 37 | + {ans= check(graph,n,m,visited,s.substr(1),i+1,j); |
| 38 | + if(ans) |
| 39 | + return true; |
| 40 | + } |
| 41 | + if(graph[i+1][j-1]==s[0] && (j-1>=0&&i+1<n)) |
| 42 | + {ans = check(graph,n,m,visited,s.substr(1),i+1,j-1); |
| 43 | + if(ans) |
| 44 | + return true; |
| 45 | + } |
| 46 | + if(graph[i][j-1]==s[0] && j-1>=0) |
| 47 | + {ans = check(graph,n,m,visited,s.substr(1),i,j-1); |
| 48 | + if(ans) |
| 49 | + return true; |
| 50 | + } |
| 51 | + visited[i][j]=false; |
| 52 | + if(ans==false) |
| 53 | + return false; |
| 54 | + |
| 55 | + |
| 56 | +} |
| 57 | +int solve(char graph[][MAXN],int N, int M) |
| 58 | +{ |
| 59 | + // Write your code here. |
| 60 | + bool visited[N][MAXN]={false}; |
| 61 | + string s="CODINGNINJA"; |
| 62 | + for(int k=0;k<N;k++) |
| 63 | + { |
| 64 | + for(int l=0;l<M;l++) |
| 65 | + { if(graph[k][l]=='C') |
| 66 | + { |
| 67 | + if(check(graph,N,M,visited,s.substr(1),k,l)) |
| 68 | + return true; |
| 69 | + } |
| 70 | + } |
| 71 | + |
0 commit comments