leetcode 之Work Search
来源:互联网 发布:计算机java就业前景 编辑:程序博客网 时间:2024/05/16 18:25
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
.
深度优先搜索。当board[i][j]==word[0]的时候调用DFS函数。
以下代码来自于 https://github.com/soulmachine/leetcode
class Solution {public: bool exist(vector<vector<char> > &board, string word) { const int m = board.size(); const int n = board[0].size(); vector<vector<bool> > visited(m, vector<bool>(n, false)); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if ((board[i][j]==word[0])&&dfs(board, word, 0, i, j, visited)) return true; return false; } private: static bool dfs(const vector<vector<char> > &board, const string &word, int index, int x, int y, vector<vector<bool> > &visited) { if (index == word.size()) //收敛条件 return true; if (x < 0 || y < 0 || x >= board.size() || y >= board[0].size()) return false; //越界,终止条件 if (visited[x][y]) //已经访问过,剪枝 return false; if (board[x][y] != word[index]) //不相等,剪枝 return false; visited[x][y] = true; bool ret = dfs(board, word, index + 1, x - 1, y, visited) || // 上 dfs(board, word, index + 1, x + 1, y, visited) || // 下 dfs(board, word, index + 1, x, y - 1, visited) || // 左 dfs(board, word, index + 1, x, y + 1, visited); // 右 visited[x][y] = false; //回溯 return ret; }};
0 0
- leetcode 之Work Search
- leetcode 之 Word Search
- Leetcode之word search
- Leetcode 之 Word Search
- leetcode之Search Insert Position
- LeetCode 之 Search Insert Position
- LeetCode之Search Insert Position
- LeetCode之Search Insert Position
- LeetCode之Search Insert Position
- leetcode 之 Search Insert Position
- LeetCode之Search Insert Position
- LeetCode之Search Insert Position
- leetcode之Search Insert Position
- 【Leetcode】之Search Insert Position
- LeetCode之Search Insert Position
- Leetcode之Word Search 问题
- How Do Search Engines Work?
- [leetcode] work break II
- iBatis简单入门
- 上级向的十个iOS面试问题
- hibernate中的组合主键的配置
- 大型网站系统架构的演化
- Java实现从网页表格导出CSV文件的例子
- leetcode 之Work Search
- 一款jquery和css3实现的卡通人物动画特效
- 不同计算机之间实现生产者-消费者问题
- 金蝶KIS专业版12.0登录时提示-8880
- Codeforces 55D Beautiful numbers (数位dp,状压辅助)
- 浅谈Adapter
- Exception in thread "main" java.lang.IllegalThreadStateException
- java获取字节的长度.
- 提高PHP代码质量36计