LeetCode 题解(10):Word Search
来源:互联网 发布:商品条形码扫描软件 编辑:程序博客网 时间:2024/03/28 22:11
题目:
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
.
题解:深度搜索 递归 308ms。程序运行时间总是超过time limit,最后压缩成如下才成功。
class Solution {public: bool exist(vector<vector<char> > &board, string word) { vector<vector<bool>> flag(board.size(), vector<bool>(board[0].size(), false)); for(size_t i = 0; i < board.size(); i++) { for(size_t j = 0; j < board[0].size(); j++) { if(board[i][j] == word[0] && dfs(flag, i, j, board, word, 0)) return true; } } return false; } bool dfs(vector<vector<bool>> & flag, size_t x, size_t y, vector<vector<char> > &board, string word, size_t start) { if(start == word.length()) return true; if(x < 0 || x >= board.size()) return false; if(y < 0 || y >= board[0].size()) return false; if(board[x][y] != word[start]) return false; if(flag[x][y]) return false; flag[x][y] = true; bool result = dfs(flag, x+1, y, board, word, start+1) || dfs(flag, x-1, y, board, word, start+1) || dfs(flag, x, y+1, board, word, start+1) || dfs(flag, x, y-1, board, word, start+1); flag[x][y] = false; return result; }};
0 0
- LeetCode 题解(10):Word Search
- LeetCode题解:Word Search
- LeetCode 题解(92): Word Search II
- 【leetcode题解】2 - Word Search
- leetcode题解-79. Word Search
- Word Search 题解
- Word Search II 题解
- LeetCode 题解(123): Add and Search Word - Data structure design
- Add and Search Word - leetcode 221号题目个人题解
- Leetcode -- Word Search(Important!)
- LeetCode(79) Word Search
- LeetCode 题解(38): Search Insert Position
- Lintcode123 Word Search solution 题解
- Lintcode132 Word Search || solution 题解
- LeetCode 题解(9):Word Break
- LeetCode 题解(87): Word Break II
- LeetCode 题解(94): Word Ladder
- LeetCode 题解(95): Word Ladder II
- 喉咙痛
- 最怕空气突然安静
- JAVA中this用法小结
- 2014美赛翻译
- 互联网产品如何攒用户,聚人气
- LeetCode 题解(10):Word Search
- LoadRunner+Android模所器实现抓包并调试本地服务端
- ebay api 对接
- 正则表达式---零宽度正预测先行断言 (?=X)
- log的获取方法
- Android Shape Drawable Resources TextView渐变 背景色 圆角
- 让UIKit(UIView,UILabel等)直接显示网页内容
- Spring3中js/css/jpg/gif等静态资源无法找到(No mapping found for HTTP request with URI)问题解决
- pom.xml 配置