knakul853

Untitled

Jun 21st, 2020
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. /**
  2. knakul853
  3. **/
  4. class Solution {
  5. public:
  6.     int dx[4] = {1,0,-1,0};
  7.     int dy[4] ={0,1,0,-1};
  8.     bool exist(vector<vector<char>>& board, string word) {
  9.        
  10.        
  11.         for(int i=0;i<board.size();i++)
  12.            for(int j=0;j<board[0].size();j++)
  13.             {
  14.                 if(board[i][j]==word[0])
  15.                 {
  16.                     board[i][j]='#';
  17.                     if(dfs(board , word , i , j ,1))return true;
  18.                     board[i][j]=word[0];
  19.                 }
  20.             }
  21.        
  22.         return false;
  23.     }
  24.    
  25.     bool dfs(vector<vector<char>>&board , string word , int i , int j,int len)
  26.     {
  27.         if(len == word.size())return true;
  28.        
  29.         for(int k=0;k<4;k++)
  30.         {
  31.             int x = i + dx[k];
  32.             int y = j + dy[k];
  33.            
  34.             if(x<0 || y<0 || x >= board.size() || y >= board[0].size())continue;
  35.             if(board[x][y]!=word[len])continue;
  36.             char temp = board[x][y];
  37.             board[x][y] = '#';
  38.            
  39.            if(dfs(board , word , x , y , len+1)){
  40.                return true;
  41.            }
  42.             board[x][y] = temp;
  43.         }
  44.         return false;
  45.          
  46.     }
  47. };
Add Comment
Please, Sign In to add comment