【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;否则,判断下一个字母
代码:
注:本来我是采用string word,int index的方法来记录每次比较到哪个字母 时间很长;后来看到讨论中用c_str() 的指针方法 发现时间迅速下降!
题目:
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() 的指针方法 发现时间迅速下降!
相关文章推荐
- 使用ShareSdk做第三方登录的一些注意点
- thrift 安装及示例
- occ代码分析
- SQL Server 数据库 'xxx' 正处于转换状态。请稍后再尝试该语句。
- vector 容器删除元素
- HDU 5009 Paint Pearls
- jquery unbind 的用法
- Permutation sequence
- 水平居中的三个例子
- WireShark 过滤语法 http://www.cnblogs.com/wangkangluo1/archive/2011/12/19/2293750.html
- HP-UX命令学习2
- Android-RoundCornerProgressBar——Android圆角进度条(Progress Bar)类库
- CheckBox定制勾选框
- 56 Merge Intervals
- 一个人的命运决定于每天晚上8点到10点之间
- IOS UI学习 UISearchBar
- 【HTML5】HTML5 高级程序设计 学习笔记Froms API
- uploadify在ie9下点击按钮后,不弹出浏览文件对话框的问题?
- switch和if判断的个人理解
- linux下iSCSI的连接总结