您的位置:首页 > 其它

【leetcode】Word Search

2015-09-14 10:48 267 查看
最近经常做到回溯的问题 但自己一直做得不是很清晰 (逻辑能力比较差,真是恨铁不成钢啊=。= 想想真是有点小难过 多加练习 希望在写递归与回溯的时候能有比较清晰的思路吧。。)

题目:

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 =

[

[“ABCE”],

[“SFCS”],

[“ADEE”]

]

word = “ABCCED”, -> returns true,

word = “SEE”, -> returns true,

word = “ABCB”, -> returns false.

解答:

看到题目,类似于寻找路径的问题,一般都会想到回溯,如果某个字母符合,则判断从这个字母出发是否存在这样一条路径,上面每个字母都符合标准,若存在 ,则为true;否则,判断下一个字母

代码:

bool exist(vector<vector<char>>& board, string word) {

int m=board.size();
if(!m) return false;
int n=board[0].size();

int len=word.length();
if(!len) return true;

for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(helper(board,i,j,m,n,word.c_str()))
return true;
}
}
return false;
}

bool helper(vector<vector<char>>& board,int i,int j,int m,int n,const char* w){

//如果待检测的下标超出 矩阵外 则false;
//若待检测的字母已被使用过 为false;
//若待检测的字母与所需字母不符 为false;
if(i<0 || j<0 || i==m || j==n || board[i][j]=='\0' || board[i][j]!=*w) return false;

//若已达 word的最后一位 即已经全部检测结束 则true
if(*(w+1)=='\0')
return true;

char tmp=board[i][j];
board[i][j]='\0';
//检测后面的字母
if(helper(board,i+1,j,m,n,w+1)||helper(board,i,j+1,m,n,w+1)|| helper(board,i-1,j,m,n,w+1)||helper(board,i,j-1,m,n,w+1))
return true;
//如果没有一条路径符合 则重置 且返回false
board[i][j]=tmp;
return false;
}


注:本来我是采用string word,int index的方法来记录每次比较到哪个字母 时间很长;后来看到讨论中用c_str() 的指针方法 发现时间迅速下降!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: