Word Search(leetcode)
2018-01-06 12:01
316 查看
Word Search(leetcode)
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 =
word =
word =
代码:
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int x = board.size();
int y = board[0].size();
bool result = false;
for(int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
result = isFound(board, i, j, word.c_str());
if (result)
return true;
}
}
return result;
}
bool isFound(vector<vector<char>>& board, int i, int j, const char* word) {
int x = board.size();
int y = board[0].size();
if (*(word) == '\0')
return true;
if (i < 0 || j < 0 || i >= x || j >= y || board[i][j] != *word)
return false;
char c = board[i][j];
board[i][j] = '#';
if (isFound(board, i-1, j, word+1) ||
isFound(board, i, j+1, word+1) ||
isFound(board, i+1, j, word+1) ||
isFound(board, i, j-1, word+1))
return true;
board[i][j] = c;
return false;
}
};
896c
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) {
int x = board.size();
int y = board[0].size();
bool result = false;
for(int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
result = isFound(board, i, j, word.c_str());
if (result)
return true;
}
}
return result;
}
bool isFound(vector<vector<char>>& board, int i, int j, const char* word) {
int x = board.size();
int y = board[0].size();
if (*(word) == '\0')
return true;
if (i < 0 || j < 0 || i >= x || j >= y || board[i][j] != *word)
return false;
char c = board[i][j];
board[i][j] = '#';
if (isFound(board, i-1, j, word+1) ||
isFound(board, i, j+1, word+1) ||
isFound(board, i+1, j, word+1) ||
isFound(board, i, j-1, word+1))
return true;
board[i][j] = c;
return false;
}
};
896c
相关文章推荐
- LeetCode *** 79. Word Search
- Leetcode-Word Search
- [Leetcode] 79. Word Search 解题报告
- [LeetCode124]Word Search
- [leetcode] 79.Word Search
- Leetcode 79:Word Search
- leetcode word search
- [Leetcode] 79. Word Search
- Leetcode 79. Word Search
- Leetcode -- Word Search
- [Leetcode] Word Search (Java)
- [leetcode] Word Search
- Leetcode 79. Word Search 要真正理解回溯的写法!
- [LeetCode] Word Search
- LeetCode 79. Word Search
- leetcode 79. Word Search 改进版本的dfs算法
- LeetCode - Word Search
- 个人记录-LeetCode 79. Word Search
- LeetCode79:Word Search
- [LeetCode] Word Search