FireEmissary

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  14 随笔 :: 0 文章 :: 20 评论 :: 0 Trackbacks
<2016年3月>
282912345
6789101112
13141516171819
20212223242526
272829303112
3456789

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜

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;
                    
    }


posted on 2016-03-26 18:41 FireEmissary 阅读(916) 评论(0)  编辑 收藏 引用