您的位置:首页 > 其它

LeetCode-Word Search

2013-08-20 10:20 267 查看
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 == "")
{
return true;
}
else if (board.size() == 0 || board[0].size() == 0)
{
return false;
}
vector<vector<bool> > used(board.size(), vector<bool>(board[0].size(), false));
for (int i = 0; i < board.size(); ++i)
{
for (int j = 0; j < board[i].size(); ++j)
{
if (existCore(board, word, 0, i, j, used))
{
return true;
}
}
}
return false;
}

bool existCore(vector<vector<char> > &board, string word, int index, int row, int col, vector<vector<bool> > &used)
{
if (board[row][col] == word[index])
{
used[row][col] = true;
++index;
if (index == word.size())
{
return true;
}
if (row > 0 && !used[row - 1][col] && existCore(board, word, index, row - 1, col, used))
{
return true;
}
if (row < board.size() - 1 && !used[row + 1][col] && existCore(board, word, index, row + 1, col, used))
{
return true;
}
if (col > 0  && !used[row][col - 1] && existCore(board, word, index, row, col - 1, used))
{
return true;
}
if (col < board[0].size() - 1 && !used[row][col + 1] && existCore(board, word, index, row, col + 1, used))
{
return true;
}
used[row][col] = false;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: