[LeetCode]Word Search
来源:互联网 发布:失业金数据与非农数据 编辑:程序博客网 时间:2024/06/08 13:40
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 Source
思路:典型的DFS算法,每次从string开始搜寻。
特别注意边界条件,每次搜寻时作标记,如果搜寻没有成功的话,标志消除。
class Solution {public: bool exist(vector<vector<char> > &board, string word) { for(int i=0;i<board.size();++i){ for(int j=0;j<board[0].size();++j){ if(dfs(board,i,j,word.begin(),word.end())) return true; } } return false; } bool dfs(vector<vector<char> >&board,int m,int n,string::iterator it,string::iterator end){ if(m<0||n<0||m>board.size()-1||n>board[0].size()-1||board[m][n]!=*it) return false; if(board[m][n]==*it&&it+1==end) return true; char temp = board[m][n]; board[m][n] = '0'; //做标记 if(dfs(board,m-1,n,it+1,end)||dfs(board,m+1,n,it+1,end)||dfs(board,m,n+1,it+1,end)||dfs(board,m,n-1,it+1,end)) { return true; } board[m][n] = temp; //没有搜寻到标记清楚,没有这条语句会报错 return false; }};
0 0
- LeetCode: Word Search
- [Leetcode] Word Search
- LeetCode : Word Search
- Leetcode: Word Search
- [LeetCode] Word Search
- leetcode 56: Word Search
- Leetcode 79 Word Search
- [leetcode ] word search
- [Leetcode] Word Search
- [LeetCode]Word Search
- Leetcode Word Search
- [leetcode]word search
- [leetcode] Word Search
- LeetCode-Word Search
- [LeetCode] Word Search
- LeetCode - Word Search
- leetcode word search
- LeetCode:Word Search
- 黑马程度员——OC语言—— 内存管理原则
- Linux button按键驱动 多次中断控制相应LED灯亮灭闪
- UILabel添加点击事件
- struts2学习之访问Servlet对象的两种实现方式
- java学习路线2
- [LeetCode]Word Search
- spring容器使用外部文件
- 排序算法之选择排序
- 学英语《每日一歌》之right here waiting
- 安卓中的socket通讯
- HDU2833 WuKong(floyd + dp)经典
- Pow(x, n)
- DirectX9 三角形单元
- 扫雷