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.

简单的单词查找,在上下左右四个方向想dfs就可以了,代码如下,注意函数之间传递引用否则会超时的:

 class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if(!word.size())
return false;
int szHor = board.size();
if(!szHor) return false;
int szVer = board[].size();
if(!szVer) return false;
vector<vector<bool>> check(szHor, vector<bool>(szVer, false));
for(int i = ; i < szHor; ++i){
for(int j = ; j < szVer; ++j){
if(board[i][j] == word[]){
check[i][j] = true;
if(word.size() == || search(word.substr(), i, j, check, board))
return true;
check[i][j] = false;
}
}
}
return false;
} bool search(string word, int i, int j, vector<vector<bool>> & check, vector<vector<char>> & board)
{
vector<vector<char>> direction{{-, }, {, }, {, -}, {, }};
for(int k = ; k < ; ++k){
int ii = direction[k][] + i;
int jj = direction[k][] + j;
if(ii >= && ii < board.size() &&
jj >= && jj < board[].size() &&
board[ii][jj] == word[] &&
check[ii][jj] == false){
check[ii][jj] = true;
if(word.size() == || search(word.substr(), ii, jj, check, board))
return true;
check[ii][jj] = false;
}
}
return false;
}
};

最新文章

  1. 关于js中的this
  2. Java 循环中标签的作用
  3. setValue:forUndefinedKey this class is not key value coding-compliant for the key
  4. 利用JS制作简便计算器
  5. webform FileUpload控件实例应用 上传图片
  6. What does &quot;Rxlch&quot; mean in ENCODE?
  7. Window环境下 Git 下载Android源码
  8. C/C++操作MySQL数据库——增、删、改、查
  9. (转)Block的使用
  10. 嵌入式Linux应用程序开发详解------(创建守护进程)
  11. jquery 获取select框选中的值示例一则
  12. yii中第三方库
  13. Couchbase的web管理员后台 查看缓存提示警告 Warning: Editing of document with size more than 2.5kb is not allowed的解决方法
  14. SQL Server 2008备份数据库失败,拒绝访问的原因
  15. suse安装svn服务端和客户端的使用
  16. dedecms学习笔记
  17. WebSphere--定制配置
  18. git恢复误删除文件
  19. Android特效专辑(四)——APP主页框架TabHost绑定ViewPager的替换者TabLayout
  20. 手动安装Package Control

热门文章

  1. Android之网络----使用HttpClient发送HTTP请求(通过get方法获取数据)
  2. 对 tensorflow 中 tf.nn.embedding_lookup 函数的解释
  3. CoreThink开发(十二)更改默认出错异常页防止暴露敏感数据
  4. day3-python的基础类源码解析——collection类
  5. python2.7中的字符编码问题
  6. json字符串转化为json对象and 对象转化为 json字符串
  7. C# int32与int64的区别 附加:字符字节关系
  8. Book Review of “The practice of programming” (Ⅲ)
  9. Maven:Eclipse上Maven的配置
  10. js 的编译