word search

要点:

1)在外层每一个格子都应用一次dfs;

2)在里层,每次使用完一个格子置为#,遍历完4个格子后,记得置为原来的值;

code


class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        int m = board.size();
        if(m == 0)
        {
            return false;
        }

        int n = board[0].size();
        bool bFound = false;
        for(int i = 0; i<m; i++)
        {
            for(int j = 0; j<n; j++)
            {
                int index = 0;
                dfs(board, i, j, index, word, bFound);
                if(bFound)
                {
                    return true;
                }
            }
        }

        return false;
    }

    void dfs(vector<vector<char>>& board, int x, int y, int index, string& word, bool& bFound)
    {

        if(bFound || index >= word.length())
        {
            bFound = true;
            return ;
        }

        int m = board.size();
        int n = board[0].size();

        if(x < 0 || x >= m || y < 0 || y >= n || board[x][y] == '#')
        {
            return ;
        }

        if(board[x][y] != word[index])
        {
            return ;
        }

        board[x][y] = '#';
        int dx[] = {0, 1, 0, -1};
        int dy[] = {1, 0, -1, 0};

        for(int i = 0; i<4; i++)
        {
            int nx = x+dx[i];
            int ny = y+dy[i];
            dfs(board, nx, ny, index+1, word, bFound);
        }
        board[x][y] = word[index];
    }
};

results matching ""

    No results matching ""