您的位置:首页 > 其它

(LeetCode 79) Word Search

2016-04-18 21:04 627 查看
Q:

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.

题意就是,给你一个二维的字符数组,然后给你一个字符串,问该字符串能不能由字符数组的一部分连接的部分构成。构成字符串的那些字符之间位置关系必须是水平或者垂直。

solution:

其实这是一道经典的回溯法,或者深度优先算法,但是C++里面的数组越界等问题真的太容易发生了,可能是自己编程习惯不够好吧。

好了,转到这道题。思路很清晰,

先找出所有与字符串第一个字符相同的字符在字符数组中的位置,然后压入栈。

再查找它上下左右有没有与字符串下一个字符匹配的位置,如果有,全部压入栈。没有,把该元素弹出栈顶。

从栈顶取一个元素,做第2步操作。

重复3操作,要么直到当前栈顶位置与字符串最后一个字符匹配,那么返回true。否则,直到栈所有元素均被弹出,成为空栈,返回false。

这里面有几点注意的:

每次弹栈压栈的是一个结构体,他包含三个信息x,y,index,分别代表该元素在字符数组的横纵下标,以及该位置与字符串的第几个字符匹配。

在一次遍历中,我们要避免再次遍历到该轮遍历已经标记为路径的位置,不然会出现无限循环,或者一个元素贡献两次。

当遍历从第n层返回到第n−1层时,从栈顶取的结点不需要再遍历,因为在之前已经遍历过,我们现在是返回到上次遍历的时候。这时候我们只需要遍历与他在同一层的兄弟结点,如果没有兄弟节点,那么就在向上一层返回。

虽然AC掉了,但是还是有些不太满意,代码有点乱。。。

class Solution {
public:
struct poxy{
int x;
int y;
int index;
poxy(int x,int y,int index):x(x),y(y),index(index){};
};

stack<poxy> pq;
vector<vector<int>> visit;

bool exist(vector<vector<char>>& board, string word) {
if(board.size()==0)return false;
if(word.length()==0)return true;

visit = vector<vector<int>>(board.size(),vector<int>(board[0].size(),0));
for(int i=0;i<board.size();i++)
for(int j=0;j<board[0].size();j++){
if(board[i][j]==word[0]){
poxy xy(i,j,0);
pq.push(xy);
}
}
int index=0;
while(!pq.empty()){
poxy txy=pq.top();
visit[txy.x][txy.y]=1;
if(txy.index==word.length()-1)return true;
if(txy.index==index-1||!findNeighbor(board,word,txy)){
visit[txy.x][txy.y]=0;
pq.pop();
}
index = txy.index;
}
return false;
}

bool findNeighbor(vector<vector<char>>& board, string word,poxy &xy){
bool flag=false;
for(int i=-1;i<=1;i++)
for(int j=-1;j<=1;j++){
if((i+j)!=-1&&(i+j)!=1)continue;
int ax=xy.x+i;
int ay=xy.y+j;
if(ax<0||ax>=board.size()||ay<0||ay>=board[0].size())continue;
if(visit[ax][ay]==1)continue;
if(board[ax][ay]==word[xy.index+1]){
flag = true;
poxy temp(ax,ay,xy.index+1);
pq.push(temp);
}
}
return flag;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 搜索 回溯