LeetCode #79
来源:互联网 发布:手机翻页电子书软件 编辑:程序博客网 时间:2024/05/02 12:56
题目描述:
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
.字符每次延伸都可以往相邻的四个方向,所以可以用递归分别搜索当前字符的四个方向,只要有一个方向可行就可以,但是要注意访问过的字符需要进行标记,之后就不能访问之前已经访问过的字符。
class Solution {public: bool exist(vector<vector<char>>& board, string word) { if(word.empty()) return true; else if(board.empty()) return false; else if(board[0].empty()) return false; for(int i=0;i<board.size();i++) { for(int j=0;j<board[0].size();j++) { if(board[i][j]==word[0]&&searchSurround(board,word,i,j,0)) return true; } } return false; } bool searchSurround(vector<vector<char>> board,string word,int i,int j,int start) { if(board[i][j]!=word[start]) return false; else if(board[i][j]==word[start]&&start==(word.size()-1)) return true; else if(board[i][j]==word[start]&&start<(word.size()-1)) { bool result=false; board[i][j]='0'; if(i>0&&board[i-1][j]!='0') result=result||searchSurround(board,word,i-1,j,start+1); if(i<(board.size()-1)&&board[i+1][j]!='0') result=result||searchSurround(board,word,i+1,j,start+1); if(j>0&&board[i][j-1]!='0') result=result||searchSurround(board,word,i,j-1,start+1); if(j<(board[0].size()-1)&&board[i][j+1]!='0') result=result||searchSurround(board,word,i,j+1,start+1); return result; } }};
阅读全文
0 0
- LeetCode #79
- 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
- leetcode 79:LWord 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
- LeetCode 79: Word Search
- Leetcode no. 79
- leetcode #79 in cpp
- GCD and LCM HDU
- pip install 出现报asciii码错误的问题
- ARP协议详解
- 【已解决】R语言添加行、列,转置操作
- rtos开发总结
- LeetCode #79
- 订餐系统总结
- HTTP Status 404错误分析及解决方法
- 9月 英语学习总结
- Qt学习: QListWidget的用法.
- 393. UTF-8 Validation
- 我的第一个JS程序——进击的马里奥
- 事件监听函数:addEventListener() removeEventListener()
- css 常见页面布局之圣杯布局(margin负值法)