leetcode---word-search---dfs

来源:互联网 发布:python matplotlib安装 编辑:程序博客网 时间:2024/05/16 12:32

Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[
[“ABCE”],
[“SFCS”],
[“ADEE”]
]
word =”ABCCED”, -> returnstrue,
word =”SEE”, -> returnstrue,
word =”ABCB”, -> returnsfalse.

class Solution {public:    int dx[4];    int dy[4];    bool dfs(int dep, int x, int y, int n, int row, int col, vector<vector<char> > &board, string word, vector< vector<bool> > &vis)    {        if(dep >= word.size())        {            return true;        }         for(int i=0; i<4; i++)        {            x += dx[i];            y += dy[i];            if(x >= 0 && x < row && y >= 0 && y < col)            {                if(!vis[x][y] && word[dep] == board[x][y])                {                    vis[x][y] = true;                    if(dfs(dep+1, x, y, n, row, col, board, word, vis))                        return true;                    vis[x][y] = false;                }            }            x -= dx[i];            y -= dy[i];        }        return false;    }    bool exist(vector<vector<char> > &board, string word)     {        int n = board.size();        if(n == 0)            return false;        int m = board[0].size();        if(m == 0)            return false;        if(word.size() == 0)            return true;        if(n * m < word.size())            return false;        dx[0] = 1;  dx[1] = -1; dx[2] = 0; dx[3] = 0;        dy[0] = 0;  dy[1] = 0;  dy[2] = 1; dy[3] = -1;        vector< vector<bool> > vis(n, vector<bool>(m, false));        for(int i=0; i<n; i++)            for(int j=0; j<m; j++)                if(board[i][j] == word[0])                {                    vis[i][j] = true;                    if(dfs(1, i, j, n*m, n, m, board, word, vis))                        return true;                    vis[i][j] = false;                }        return false;    }};
原创粉丝点击