标签:
iven 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
.
回溯法:
class Solution { public: bool search(vector<vector<char> > &board,const string word,int i,int j,int pos){ if(pos==word.size())return true; if(i<0||i>=board.size()||j<0||j>=board[i].size())return false; char ch=board[i][j]; if(ch==word[pos]){ board[i][j]=‘#‘;//标记为已访问过的点 if(search(board,word,i-1,j,pos+1)||search(board,word,i+1,j,pos+1) ||search(board,word,i,j-1,pos+1)||search(board,word,i,j+1,pos+1)) return true; board[i][j]=ch;//回溯失败则变成上一个状态 } return false; } bool exist(vector<vector<char> >& board, string word) { for(int i=0;i<board.size();i++){ for(int j=0;j<board[i].size();j++){ if(search(board,word,i,j,0)) return true;//寻找第一个匹配的位置,然后通过回溯求解 } } return false; } };
标签:
原文地址:http://www.cnblogs.com/wqkant/p/5389050.html