您的位置:首页 > 其它

leetCode刷题归纳-backtracking(79. Word Search)

2017-06-10 14:41 357 查看

题目描述

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.

解题思路

在二维数组中寻找字符串的匹配,使用回溯+贪心算法解决:

isFound是构造的辅助函数,主要用来检测是否发现了下一个搜索点

还需要稍微注意一下边界值的判断:搜索到最后一个字符怎么办?没有搜索点怎么办?(这里我采取的方法是都丢进isFound函数解决)

class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if(board.empty()||word.size()==0) return false;
m=board.size(),n=board[0].size();
//char *w=&word[0];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++){
if(isFound(board,word.c_str(),i,j)) return true;
}
return false;
}
bool isFound(vector<vector<char> > &board, const char* w, int x, int y){
if(x>=m||x<0||y<0||y>=n||*w!=board[x][y])  return false;
if(*(w+1)=='\0')  return true;
char tmp=board[x][y];
board[x][y]='\0';
if(isFound(board,w+1,x+1,y)||isFound(board,w+1,x-1,y)||isFound(board,w+1,x,y+1)||isFound(board,w+1,x,y-1))
return true;
board[x][y]=tmp;

return false;
}
private:
int m,n;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: