leedcode 79. Word Search

leedcode 79. Word Search

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board =

[   ['A','B','C','E'],   ['S','F','C','S'],   ['A','D','E','E'] ] 
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

访问过的元素不能再访问,发现大家的实现都是用个附加结构标记访问过的.就地赋值个'\0'后面再恢复好啦.......

  bool  exist(vector < vector < char >>&  board, int  i, int  j, string ::iterator beg, string ::iterator end)
   {
       
bool  res = true ;
       
char  cur =* beg ++ ;
       
if (board[i][j] != cur) return   false ;
       
if (beg == end) return   true ;   
       board[i][j]
= 0 ;
       
do { // 上下左右
         if (i + 1 < board.size() && exist(board,i + 1 ,j,beg,end))
           
break ;
        
if (i - 1 >= 0 && exist(board,i - 1 ,j,beg,end))
          
break ;
        
if (j + 1 < board[ 0 ].size() && exist(board,i,j + 1 ,beg,end))
           
break ;
          
if (j - 1 >= 0 &&  exist(board,i,j - 1 ,beg,end))
            
break ;
            res
= false ;
         }
while ( 0 );
        board[i][j]
= cur; 
       
return  res;
   }
    
bool  exist(vector < vector < char >>&  board,  string  word) {
          
char  beg = word[ 0 ];
          
for ( int  i = 0 ;i < board.size(); ++ i)
            
for ( int  j = 0 ;j < board[ 0 ].size(); ++ j)
                
if (exist(board,i,j,word.begin(),word.end()))
                    
return   true ;
        
return   false ;
                    
    }


你可能感兴趣的:(leedcode 79. Word Search)