Word Search [leetcode]
来源:互联网 发布:oimo.js 编辑:程序博客网 时间:2024/06/03 14:55
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
.
解法:DFS
bool exist(vector<vector<char> > &board, string word) { int m = board.size(); if (m == 0) return false; int n = board[0].size(); if (n == 0) return false; if (word.size() == 0) return false; vector<int> x; vector<int> y; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if (board[i][j] == word[0]) { x.push_back(i); y.push_back(j); } for (int i = 0; i < x.size(); i++) { if (dfs(board, word, 1, x[i], y[i], m, n)) return true; } return false; } bool dfs(vector<vector<char> > &board, string& word, int index, int x, int y, int m, int n) { if (index == word.size()) return true; char temp = board[x][y]; board[x][y] = '.'; bool res = false; if (x > 0 && board[x - 1][y] == word[index]) res |= dfs(board, word, index + 1, x - 1, y, m, n); if (res) return true; if (x < m - 1 && board[x + 1][y] == word[index]) res |= dfs(board, word, index + 1, x + 1, y, m, n); if (res) return true; if (y > 0 && board[x][y - 1] == word[index]) res |= dfs(board, word, index + 1, x, y - 1, m, n); if (res) return true; if (y < n - 1 && board[x][y + 1] == word[index]) res |= dfs(board, word, index + 1, x, y + 1, m, n); if (res) return true; board[x][y] = temp; return res; }
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
- Django中的lambda函数
- The substring() Method in JDK 6 and JDK 7 (jdk6中的substring()会造成内存泄漏)
- java 自动装箱与拆箱
- MATLAB GUI对话框设计
- 图论算法(6)(更新版) --- Tarjan算法求强连通分量
- Word Search [leetcode]
- 怎么上谷歌E9加速器分享安卓平板怎么上Google注册gmail
- windows server 2012 活动目录部署系列(七)域控制器的常规卸载
- PDU编码(非常经典)
- 内存泄露简述
- QRadioButton分组且无边框的简单实现
- 列书闲读
- hdu 5038 Grade(水题)
- Minimum Window Substring [leetcode]