Word Search问题及解法
来源:互联网 发布:linux epoll socket 编辑:程序博客网 时间:2024/05/18 17:44
问题描述:
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.
示例:
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
.问题分析:
此类查找问题,可采用回溯法。
过程详见代码:
class Solution {public: bool exist(vector<vector<char>>& board, string word) {if (word.empty()) return false;int m = board.size();int n = board[0].size();vector<vector<int>> used(m,vector<int>(n, 0));for (int i = 0; i < m; i++){for (int j = 0; j < n; j++){if (board[i][j] == word[0]){bool res = search(board, word, i, j, 1, used);if (res) return true;}}}return false;}bool search(vector<vector<char>>& board, string word, int i, int j, int k, vector<vector<int>>& used){used[i][j] = 1;if (k == word.length()){if (board[i][j] == word[k - 1]) return true;}if (board[i][j] == word[k - 1]){bool res = false;if (j < board[0].size() - 1 && !used[i][j + 1]){res = res || search(board, word, i, j + 1, k + 1, used);if (res) return true;}if (i + 1 < board.size() && !used[i + 1][j]){res = res || search(board, word, i + 1, j, k + 1, used);if (res) return true;}if (j - 1 >= 0 && !used[i][j - 1]){res = res || search(board, word, i, j - 1, k + 1, used);if (res) return true;}if(i - 1 >= 0 && !used[i - 1][j]){res = res || search(board, word, i - 1, j, k + 1, used);if (res) return true;}used[i][j] = 0;return res;}used[i][j] = 0;return false;}};
阅读全文
0 0
- Word Search问题及解法
- Word Pattern问题及解法
- Word Ladder问题及解法
- Word Break问题及解法
- Search Insert Position问题及解法
- Search for a Range问题及解法
- Unique Binary Search Trees问题及解法
- Validate Binary Search Tree问题及解法
- Binary Search Tree Iterator问题及解法
- Length of Last Word问题及解法
- Longest Word in Dictionary问题及解法
- Convert Sorted Array to Binary Search Tree问题及解法
- Find Mode in Binary Search Tree问题及解法
- Search in Rotated Sorted Array问题及解法
- Search a 2D Matrix问题及解法
- Search in Rotated Sorted Array II问题及解法
- Unique Binary Search Trees II问题及解法
- Convert Sorted List to Binary Search Tree问题及解法
- OSPF
- HashSet
- vue动态数据绑定3--深层次数据变化逐层往上传播
- [caioj]【计算几何】判断线段相交(跨立实验) 计算几何 叉积
- [Poi2014]FarmCraft 树状dp
- Word Search问题及解法
- XYNUOJ 1252: NOIP2007普及组第2题 纪念品分组
- Struts2中使用国际化
- 2015多校第8场 HDU 5386 Cover 贪心,暴力,玄学
- 读前辈的大话设计模式(二)之策略模式,抒自己的读后感
- Linux-网编程络
- HDU
- Date和String转换,正则表达式
- Codeforces 835D Palindromic characteristics【区间Dp】