您的位置:首页 > 其它

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 =
[
['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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: