[LeetCode] Word Search
来源:互联网 发布:html js 视频教程下载 编辑:程序博客网 时间:2024/05/21 08:57
Word Search
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
.解题思路:
回溯法。用一个二维数组标记是否已经访问,然后朝上下左右四个方向进行扩展即可。
class Solution {public: bool exist(vector<vector<char>>& board, string word) { int len = word.length(); if(len==0){ return true; } int m = board.size(); if(m==0){ return false; } int n = board[0].size(); if(n==0){ return false; } vector<vector<bool>> flag(m, vector<bool>(n, false)); for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(helper(board, flag, i, j, 0, word)){ return true; } } } return false; } bool helper(vector<vector<char>>& board, vector<vector<bool>>& flag, int i, int j, int index, string& word){ if(index>=word.length()){ return true; } int m = board.size(); int n = board[0].size(); if(i<0 || i>=m || j<0 || j>=n || flag[i][j] || board[i][j]!=word[index]){ return false; } flag[i][j] = true; bool result = helper(board, flag, i+1, j, index + 1, word) || helper(board, flag, i, j+1, index + 1, word) || helper(board, flag, i-1, j, index + 1, word) || helper(board, flag, i, j-1, index + 1, word); flag[i][j] = false; return result; }};
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
- lua和V8 JavaScript初学中,,,,(二)
- javascript 解析json的代码
- tomcat部署web项目的3中方法
- 用Spring将Service注入到Servlet中
- hdu1420
- [LeetCode] Word Search
- CBitmap转换成GDI+的Bitmap (Image)
- PAAS平台对比:OpenShift VS CloudFoundry【51CTO调研报告】
- iOS-UI-tabelView
- 如何在eclipse中导入两个相同的工程
- 转载_蓝牙协议栈架构
- jQuery只网站品牌列表的效果
- SGU167
- hdu4506 小明系列故事——师兄帮帮忙 解题报告