# FireEmissary

C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
 14 随笔 :: 0 文章 :: 20 评论 :: 0 Trackbacks

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`.

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 阅读(892) 评论(0)  编辑 收藏 引用