1. 程式人生 > >[leetcode] Word Search

[leetcode] Word Search

dfs,程式碼如下:

class Solution {
public:
    bool exist(vector<vector<char> > &board, string word) {
        const int row = board.size();
        const int column = board[0].size();
        vector<vector<bool> > visited(row, vector<bool>(column, false));
        for(int i = 0; i < row; ++i)
            for(int j = 0; j < column; ++j)
                if(dfs(board, word, 0, i, j, visited))
                    return true;
        return false;
    }
private:
    bool dfs(vector<vector<char> > &board, string word, int count, int x, int y, vector<vector<bool> > &visited){
        if(count == word.length())
            return true;
        if(x < 0 || x > board.size() - 1)
            return false;
        if(y < 0 || y > board[0].size() - 1)
            return false;
        if(visited[x][y])
            return false;
        if(board[x][y] == word[count])
        {
            visited[x][y] = true;
            if(dfs(board, word, count + 1, x - 1, y, visited) ||
                dfs(board, word, count + 1, x, y - 1, visited) ||
                dfs(board, word, count + 1, x + 1, y, visited) ||
                dfs(board, word, count + 1, x, y + 1, visited))
                return true;
            visited[x][y] = false;
            return false;
        }
        return false;
    }
};