leetCode刷题归纳-backtracking(79. Word Search)
2017-06-10 14:41
357 查看
题目描述
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.
解题思路
在二维数组中寻找字符串的匹配,使用回溯+贪心算法解决:isFound是构造的辅助函数,主要用来检测是否发现了下一个搜索点
还需要稍微注意一下边界值的判断:搜索到最后一个字符怎么办?没有搜索点怎么办?(这里我采取的方法是都丢进isFound函数解决)
class Solution { public: bool exist(vector<vector<char>>& board, string word) { if(board.empty()||word.size()==0) return false; m=board.size(),n=board[0].size(); //char *w=&word[0]; for(int i=0;i<m;i++) for(int j=0;j<n;j++){ if(isFound(board,word.c_str(),i,j)) return true; } return false; } bool isFound(vector<vector<char> > &board, const char* w, int x, int y){ if(x>=m||x<0||y<0||y>=n||*w!=board[x][y]) return false; if(*(w+1)=='\0') return true; char tmp=board[x][y]; board[x][y]='\0'; if(isFound(board,w+1,x+1,y)||isFound(board,w+1,x-1,y)||isFound(board,w+1,x,y+1)||isFound(board,w+1,x,y-1)) return true; board[x][y]=tmp; return false; } private: int m,n; };
相关文章推荐
- LeetCode 79. Word Search(单词查找)
- LeetCode_79 Word Search
- [leetcode] 79.Word Search
- leetcode || 79、Word Search
- LeetCode39/40/22/77/17/401/78/51/46/47/79 11道回溯题(Backtracking)
- *LeetCode 79. Word Search DFS
- leetcode.array--79. Word Search
- 第十六周:[leetCode] 79. Word Search
- leetcode 79. Word Search
- [LeetCode] 79. Word Search 单词搜索
- Leetcode-79_Word Searchr-典型深搜题-【C++】
- 【LeetCode】79. Word Search
- Leetcode 79. Word Search
- Leetcode 79:Word Search
- [leetcode] 79. Word Search 解题报告
- 【LeetCode]79. Word Search
- 个人记录-LeetCode 79. Word Search
- leetcode 79. Word Search 改进版本的dfs算法
- [python]leetcode(79). Word Search
- LeetCode 79 Word Search (Python详解及实现)