[Leetcode] Word Search

来源:互联网 发布:python alphalens 编辑:程序博客网 时间:2024/04/26 03:18
class Solution {public:    bool exist(vector<vector<char> > &board, string word) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        vector<point> used;                for (int i = 0; i < board.size(); ++i)        {            for (int j = 0; j < board[0].size(); ++j)            {                if (search(0, word, board, i, j, used))                    return true;            }        }                return false;            }        struct point    {        int x;        int y;        bool operator== (point p) const        {            if (x == p.x && y == p.y)                return true;            return false;        }    };        bool search(int idx, string& word, vector<vector<char> >& board, int i, int j, vector<point> used)    {        if (i >= board.size() || j >= board[0].size() || i < 0 || j < 0) return false;                point p; p.x = i; p.y = j;                for (int i = 0; i < used.size(); ++i)        {            if (used[i] == p)                return false;        }                    if (word[idx] == board[i][j])        {            if (idx == word.size() - 1)                return true;                        used.push_back(p);            return search(idx + 1, word, board, i + 1, j, used) ||                    search(idx + 1, word, board, i - 1, j , used) ||                    search(idx + 1, word, board, i, j - 1, used) ||                    search(idx + 1, word, board, i, j + 1, used);        }                   return false;    }        };

原创粉丝点击