您的位置:首页 > 编程语言 > C语言/C++

leetcode 79. Word Search

2017-02-10 19:16 639 查看
class Solution {
public:
bool exist(vector<vector<char>>& board, string word)
{
if (board.empty())
{
return false;
}
row = board.size();
col = board[0].size();
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
process(board, word, 0, i, j);
if (res == true)
{
return res;
}
}
}
return res;
}

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