leetCode刷题归纳-backtracking(79. Word Search)
来源:互联网 发布:深入浅出mysql 百度云 编辑:程序博客网 时间:2024/06/15 17:21
题目描述
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;};
阅读全文
0 0
- leetCode刷题归纳-backtracking(79. Word Search)
- (M)Backtracking:79. Word Search
- leetCode刷题归纳-backtracking(39. Combination Sum I && II)
- 【Leetcode】Word Ladder II (Backtracking)
- 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
- 79. Word Search LeetCode
- leetcode 79. Word Search
- LeetCode 79. Word Search
- LeetCode 79. Word Search
- leetcode 79. Word Search
- LeetCode *** 79. Word Search
- [leetcode] 79. Word Search
- ARM NEON 基本指令集介绍
- 互联网公司的“敏捷开发”流程是怎么样的,每个职位的角色和分工是什么?
- 位置式和增量式PID控制 .
- 81-85.c++个人练习。
- |Poj 3581|后缀数组|Sequence
- leetCode刷题归纳-backtracking(79. Word Search)
- 程序员的自我修养——7、动态链接
- IDEA配置jdk
- java关键字-final
- 中国考试机器人挑战高考题,最高得分105
- 毕业了,新的开始
- Python初识
- MySQL的查询缓存功能现已成了瓶颈!
- Python 3.5安装pyMySQL错误“error: Microsoft Visual C++ 14.0 is required…”