Word Search

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.

回溯法(关于回溯法和深度优先遍历的异同),而且递归在leetcode里基本上是TLE的,所以以下就是非递归的回溯。

核心思想如下:

用栈记录当前搜索的路径。

栈存放的节点包括4个成员: 字符c, x,y坐标,已遍历方向p。

注意p在回溯法中是非常重要的,用来记录已遍历过的方向(按照上下左右的顺序),不然的话就会出现无限循环的同一节点进栈出栈。

进栈之后的节点置为'*',以免同一节点多次进栈。

出栈之后的节点恢复为word[wind]。

struct Node
{
char c;
int x;
int y;
int p; //next trial is 0-up, 1-down, 2-left, 3-right
Node(char newc, int newx, int newy, int newp): c(newc), x(newx), y(newy), p(newp) {}
}; class Solution {
public:
bool exist(vector<vector<char> > &board, string word) {
if(board.empty() || board[].empty())
return false;
int m = board.size();
int n = board[].size(); for(int i = ; i < m; i ++)
{
for(int j = ; j < n; j ++)
{
if(board[i][j] == word[])
{// maybe a success
stack<Node> stk;
Node curnode(word[], i, j, );
stk.push(curnode);
board[curnode.x][curnode.y] = '*';
int wind = ;
if(wind == word.size())
return true;
while(!stk.empty())
{
if(stk.top().p == )
{
stk.top().p = ;
if(stk.top().x > && board[stk.top().x-][stk.top().y] == word[wind])
{
Node nextnode(word[wind], stk.top().x-, stk.top().y, );
stk.push(nextnode);
board[nextnode.x][nextnode.y] = '*';
wind ++;
if(wind == word.size())
return true;
continue;
}
}
if(stk.top().p == )
{
stk.top().p = ;
if(stk.top().x < m- && board[stk.top().x+][stk.top().y] == word[wind])
{
Node nextnode(word[wind], stk.top().x+, stk.top().y, );
stk.push(nextnode);
board[nextnode.x][nextnode.y] = '*';
wind ++;
if(wind == word.size())
return true;
continue;
}
}
if(stk.top().p == )
{
stk.top().p = ;
if(stk.top().y > && board[stk.top().x][stk.top().y-] == word[wind])
{
Node nextnode(word[wind], stk.top().x, stk.top().y-, );
stk.push(nextnode);
board[nextnode.x][nextnode.y] = '*';
wind ++;
if(wind == word.size())
return true;
continue;
}
}
if(stk.top().p == )
{
stk.top().p = ;
if(stk.top().y < n- && board[stk.top().x][stk.top().y+] == word[wind])
{
Node nextnode(word[wind], stk.top().x, stk.top().y+, );
stk.push(nextnode);
board[nextnode.x][nextnode.y] = '*';
wind ++;
if(wind == word.size())
return true;
continue;
}
}
//restore
board[stk.top().x][stk.top().y] = stk.top().c;
stk.pop();
wind --;
}
}
}
}
return false;
}
};

【LeetCode】79. Word Search的更多相关文章

  1. 【LeetCode】79. Word Search 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 回溯法 日期 题目地址:https://leetco ...

  2. 【leetcode】212. Word Search II

    Given an m x n board of characters and a list of strings words, return all words on the board. Each ...

  3. 【一天一道LeetCode】#79. Word Search

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...

  4. 【LeetCode】212. Word Search II 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 前缀树 日期 题目地址:https://leetco ...

  5. 【LeetCode】Longest Word in Dictionary through Deleting 解题报告

    [LeetCode]Longest Word in Dictionary through Deleting 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode. ...

  6. 【LeetCode】二叉查找树 binary search tree(共14题)

    链接:https://leetcode.com/tag/binary-search-tree/ [220]Contains Duplicate III (2019年4月20日) (好题) Given ...

  7. 【LeetCode】Validate Binary Search Tree ——合法二叉树

    [题目] Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defin ...

  8. 【leetcode】 Unique Binary Search Trees (middle)☆

    Find the contiguous subarray within an array (containing at least one number) which has the largest ...

  9. LeetCode OJ 79. Word Search

    题目 Given a 2D board and a word, find if the word exists in the grid. The word can be constructed fro ...

随机推荐

  1. maven生命周期(lifecycle)—— maven权威指南学习笔记(四)

    定义: 生命周期是包含在一个项目构建中的一系列有序的阶段 举个例子来说就是maven 对一个工程进行: 验证(validate) …… 编译源码(compile) …… 编译测试源码(test-com ...

  2. 【BestCoder】【Round#41】

    枚举+组合数?+DP+数学问题 http://bestcoder.hdu.edu.cn/contests/contest_show.php?cid=582 QAQ许久没打过比赛,来一发BC,结果还是只 ...

  3. ffmpeg 2.3版本号, 关于ffplay音视频同步的分析

    近期学习播放器的一些东西.所以接触了ffmpeg,看源代码的过程中.就想了解一下ffplay是怎么处理音视频同步的,之前仅仅大概知道通过pts来进行同步,但对于怎样实现却不甚了解,所以想借助这个机会, ...

  4. go语言基础之结构体成员的使用普通变量

    1.结构体成员的使用普通变量 示例: package main //必须有个main包 import "fmt" //定义一个结构体类型 type Student struct { ...

  5. std::vector利用swap()函数进行内存的释放【转】

    首先,vector与deque不同,其内存占用空间只会增长,不会减小.比如你首先分配了10,000个字节,然后erase掉后面9,999个,则虽然有效元素只有一个,但是内存占用仍为10,000个.所有 ...

  6. 泛型 Generic 类型擦除引起的问题及解决方法

    参考:http://blog.csdn.net/lonelyroamer/article/details/7868820#comments 因为种种原因,Java不能实现真正的泛型,只能使用类型擦除来 ...

  7. Bootstrap学习js插件篇之下拉菜单

    案例 通过此插件可以为几乎所有东西添加下拉菜单,包括导航条.标签页.胶囊式按钮. 用于导航条 导航条分为四个部分.第一部分导航头,第二部分导航列,第三部分form查询表单,第四部分导航列. <n ...

  8. 用于Web开发的8 个最好的跨平台编辑器

    1) Best Cross Platform IDE - Brackets Brackets是一个在前端Web开发和设计人员中最流行的开放源码IDE/代码编辑器之一.它拥有一些实用工具能够将HTML ...

  9. Android -- ImageLoader本地缓存

    传送门 <Android -- ImageLoader简析>  http://www.cnblogs.com/yydcdut/p/4008097.html 本地缓存 在缓存文件时对文件名称 ...

  10. Redis自学笔记 --string类型

    string类型                                                                                  set 赋值 get ...