Leetcode-79. Word Search
2017-03-26 16:24
423 查看
题目
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.
求解给定字符串word,是否在字符矩阵board 中。要求word中相邻的两个字符,在board 中也是相邻字符,并且要求,board 中的同一字符,不能使用两次;
思路
使用dfs. 先在矩阵中找到word[0],若找到,就执行search函数继续查找。递归结束条件是 index == word.length(); 如果是超过边界或者board[i != word[index] 就return false。 为防止same letter cell may be used more than once, 要标记已经访问过的letter为 #. 每次递归结束以后还要还原以防影响下一次。代码
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[i].size(); j++) { if (board[i][j] == word[0]) { if(search(i, j, 0, word, board)) return true; } } } return false; } bool search(int i, int j, int index, string &word, vector<vector<char> >& board) { if(index == word.size()) return true; if( i < 0 || j < 0 || i >= board.size()|| j >= board[0].size() || board[i][j] != word[index]) { return false; } char c = board[i][j]; board[i][j] = '#'; bool rst = search(i + 1, j, index + 1, word, board) || search(i, j + 1, index + 1, word, board) || search(i, j - 1, index + 1, word, board) || search(i - 1, j, index + 1, word, board); board[i][j] = c; return rst; } };
相关文章推荐
- leetcode 79|212. Word Search 1|2
- leetcode 79. Word Search DFS 单词搜索 + 深度优先遍历
- (java)leetcode-79:Word Search
- [leetCode]79(Word Search)
- Leetcode 79 Word Search
- LeetCode - 79 - Word Search
- Leetcode 79. Word Search
- (Java) LeetCode 79. Word Search —— 单词搜索
- leetcode79——Word Search
- leetcode 79. Word Search
- LeetCode 79 Word Search (Python详解及实现)
- 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. Word Search
- LeetCode 79. Word Search(单词查找)