Leetcode算法79 Word Search
来源:互联网 发布:oppo手机root软件 编辑:程序博客网 时间:2024/06/05 16:48
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.length() == 0){return true;}char c = word[0];bool res = false;for (int i = 0; i < board.size(); i++){for (int j = 0; j < board[0].size(); j++){if (board[i][j] == c){board[i][j] = '.';res = search(board, word, i, j, 1);board[i][j] = c;if (res){return res;}}}}return res;}bool search(vector<vector<char>> &board, string word, int low, int row, int index){if (index == word.length()){return true;}bool res = false;char c = word[index];if (low>0 && board[low - 1][row] == c){board[low - 1][row] = '.';res = search(board, word, low - 1, row, index + 1);if (res)return res;board[low - 1][row] = c;}if (low < (board.size() - 1) && board[low + 1][row] == c){board[low + 1][row] = '.';res = search(board, word, low + 1, row, index + 1);if (res) return res;board[low + 1][row] = c;}if (row > 0 && board[low][row - 1] == c){board[low][row - 1] = '.';res = search(board, word, low, row - 1, index + 1);if (res) return res;board[low][row - 1] = c;}if (row < board[0].size() - 1 && board[low][row + 1] == c){board[low][row + 1] = '.';res = search(board, word, low, row + 1, index + 1);if (res) return res;board[low][row + 1] = c;}return res;}};
0 0
- Leetcode算法79 Word Search
- leetcode 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
- 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
- 日请求亿级的QQ会员AMS平台PHP7升级实践
- 第15节--神经网络应用--异或判断、手写数字识别
- 学习SQL需要了解的一些简单的命令
- 重识JavaScript(一)
- Flutter基础—质感设计
- Leetcode算法79 Word Search
- SQLserver查询所有表和表下面所有列
- 【LeetCode】300. Longest Increasing Subsequence
- 2016/11/1学习工作日志
- Unity插件MapNav2学习笔记
- linux驱动 自旋锁
- 算法基础复习-SelectionSort
- [LeetCode]Text Justification
- Android 开机启动过程