LeetCode-Word Search

来源:互联网 发布:jquery.tooltip.js 编辑:程序博客网 时间:2024/04/19 21:46
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;    }};

原创粉丝点击