LeetCode —— Word Search
2013-04-22 19:34
183 查看
链接:http://leetcode.com/onlinejudge#question_79
原题:
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 =
word =
-> returns
word =
-> returns
word =
-> returns
思路:dfs搜索,按四个方向走,不断回溯
const int Solution::dir[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
代码:
原题:
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搜索,按四个方向走,不断回溯
const int Solution::dir[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
代码:
class Solution { public: bool exist(vector<vector<char> > &board, string word) { // Start typing your C/C++ solution below // DO NOT write int main() function if (word.size()==0) return true; if (board.size()==0) return false; int rows = board.size(); int cols = board[0].size(); vector<vector<bool> > used; for (int i=0; i<rows; i++) used.push_back(vector<bool>(cols)); for (int i=0; i<rows; i++) { for (int j=0; j<cols; j++) { if (word[0]==board[i][j]) { used[i][j] = true; if (dfs(board, used, word, 1, i, j)) return true; used[i][j] = false; } } } return false; } private: static const int dir[4][2]; bool dfs(const vector<vector<char> > &board, vector<vector<bool> > &used, const string &word, int n, int x, int y) { if (n==word.size()) return true; int rows = board.size(); int cols = board[0].size(); for (int i=0; i<4; i++) { int nx = x + dir[i][0]; int ny = y + dir[i][1]; if (nx>=0 && nx<rows && ny>=0 && ny<cols) { if (!used[nx][ny] && word ==board[nx][ny]) { used[nx][ny] = true; if (dfs(board, used, word, n+1, nx, ny)) return true; used[nx][ny] = false; } } } return false; } }; const int Solution::dir[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
相关文章推荐
- leetcode-Word Search
- [leetcode] Word Search
- LeetCode解题笔记79 Word Search
- LeetCode - Word Search
- 【LeetCode-面试算法经典-Java实现】【079-Word Search(单词搜索)】
- LeetCode上面一道算法题目:79. Word Search
- Leetcode 之 Word Search
- 【leetcode题解】2 - Word Search
- Leetcode79 Word Search
- (Java) LeetCode 79. Word Search —— 单词搜索
- Leetcode: Word Search
- [Leetcode]Word Search
- [LeetCode] Word Search
- [LeetCode124]Word Search
- [LeetCode] Word Search
- LeetCode(79) Word Search
- [Leetcode]@python 79. Word Search
- leetcode_079 Word Search
- [LeetCode]Word Search
- LeetCode 79(Word Search)java