leetcode-79-单词搜索

class Solution {

public:

    vector<vector<int>> move = {{0,1}, {1,0}, {0,-1}, {-1,0}}; //右下左上

    vector<vector<bool>> visited;

    bool outofArea(vector<vector<char>> board, int y, int x){

        return !(x>=0 && y>=0 && y<board.size() && x<board[0].size());

    }

    bool search(vector<vector<char>>& board, string word, int y, int x){

        if (word.length() == 0) return true;

        for (int i=0; i<4; i++){

            int newx = x + move[i][1];

            int newy = y + move[i][0];

            if (outofArea(board, newy, newx)) continue;

            if (!visited[newy][newx] && board[newy][newx] == word[0]){//匹配成功了且没有用过

                visited[newy][newx] = true;

                if (search(board, word.substr(1), newy, newx)) return true;

                visited[newy][newx] = false;

            }

        }

        return false;

    }

    bool exist(vector<vector<char>>& board, string word) {

        visited = vector<vector<bool>> (board.size(), vector<bool>(board[0].size(), false));

        for (int i=0; i<board.size(); i++){//y

            for (int j=0; j<board[i].size(); j++){//x

                if (board[i][j] == word[0]){

                    visited[i][j] = true;

                    if (search(board, word.substr(1), i, j)) return true;

                    visited[i][j] = false;

                }

            }

        }

        return false;

    }

};

相关文章: