[LeetCode]Word Search

来源:互联网 发布:php免费空间有哪些 编辑:程序博客网 时间:2024/04/26 23:49
int Dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};class Solution {//DFS Find the pathpublic:void DFS(int curX, int curY, int curPos, vector<vector<bool>>& visit, bool& OK, vector<vector<char>> &board, string& word ){if(OK) return;if(word[curPos] != board[curX][curY]) return;if(curPos == word.size()-1){OK = true;return;}for (int d = 0; d < 4; ++d){int nextX = curX+Dir[d][0];int nextY = curY+Dir[d][1];if(nextX >= 0 && nextX < board.size() && nextY >= 0 && nextY < board[0].size()){if(!visit[nextX][nextY]){visit[nextX][nextY] = true;DFS(nextX, nextY, curPos+1, visit, OK, board, word);visit[nextX][nextY] = false;}}}}public:bool exist(vector<vector<char> > &board, string word) {// Start typing your C/C++ solution below// DO NOT write int main() functionif(word.size() == 0) return false;if(board.size() == 0 || board[0].size() == 0) return false;bool OK = false;vector<vector<bool>> visit(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){visit[i][j] = true;DFS(i, j, 0, visit, OK, board, word);visit[i][j] = false;if(OK) return true;}}return false;}};

second time

class Solution {public:    int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};    bool findPath(vector<vector<char> > &board, string& word, vector<vector<bool> >& used, int curX, int curY, int curIdx)    {        int n = board.size();        int m = board[curX].size();        if(curIdx == word.size()) return true;        for(int k = 0; k < 4; ++k)        {            int newX = curX+dir[k][0];            int newY = curY+dir[k][1];            if(newX >= 0 && newX < n && newY >= 0 && newY < m && used[newX][newY] == false && board[newX][newY] == word[curIdx])            {                used[newX][newY] = true;                if(findPath(board, word, used, newX, newY, curIdx+1)) return true;                used[newX][newY] = false;            }        }        return false;    }    bool exist(vector<vector<char> > &board, string word) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(word.size() == 0) return true;        int n = board.size();        if(n == 0) return false;        int m = board[0].size();                vector<vector<bool> > used(n, vector<bool>(n, false));        for(int i = 0; i < board.size(); ++i)        {            for(int j = 0; j < board[i].size(); ++j)            {                if(board[i][j] == word[0])                {                    used[i][j] = true;                    if(findPath(board, word, used, i, j, 1)) return true;                    used[i][j] = false;                }            }        }        return false;    }};


原创粉丝点击