Word Search

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" , -> returns  true ,
word  =  "SEE" , -> returns  true ,

word = "ABCB", -> returns false.

从board的任何一个位置开始进行DFS,如果找到一个匹配,则返回true,否则返回false。

用一个和board同样大小的bool数组标记每个位置是否已经访问过,防止重复访问。注意DFS的几种结束条件(不匹配,长度越界,坐标越界,匹配到最后一个字符(返回true))。时间复杂度O(m^2*n^2),空间O(mn)。

class Solution {
public:
    bool exist(vector<vector<char> > &board, string word) {
        const int m = board.size();
        const int n = board[0].size();
        vector<vector<bool> > visited(m, vector<bool>(n, false));
        for(int i=0; i<m; ++i)
            for(int j=0; j<n; ++j)
                if(dfs(board, visited, i, j, 0, word))
                    return true;
        return false;
    }
    bool dfs(vector<vector<char> > &board, vector<vector<bool> > &visited, int m, int n, int index, string &word)
    {
        if(index == word.size())
            return true;
        if(m < 0 || m >= board.size() || n < 0 || n >= board[0].size())
            return false;
        if(visited[m][n])
            return false;
        if(board[m][n] != word[index])
            return false;
        
        visited[m][n] = true;
        bool flag = dfs(board, visited, m+1, n, index+1, word) ||
                    dfs(board, visited, m, n+1, index+1, word) ||
                    dfs(board, visited, m-1, n, index+1, word) ||
                    dfs(board, visited, m, n-1, index+1, word);
        visited[m][n] = false;
        return flag;
    }
};

Method 2:非递归实现。注意使用set来对当前Path上的字符判重。





class Solution {
public:
    bool exist(vector<vector<char> > &board, string word) {
        const int rows = board.size();
        const int cols = board[0].size();
        vector<vector<bool> > visited(rows, vector<bool>(cols, false));
        
        for(int i=0; i<rows; i++)
        {
            for(int j=0; j<cols; j++)
            {
                if(board[i][j] == word[0] && dfs(board, visited, word, i, j)) return true;
            }
        }
        return false;
    }
    
    bool dfs(vector<vector<char> > &board, vector<vector<bool> > &visited, string &word, int i, int j)
    {
        stack<pair<pair<int, int>, int> > stack;
        
        int idx = 0;
        
        stack.push(make_pair(make_pair(i, j), 0));
        while(!stack.empty())
        {
            pair<int, int> &pos = stack.top().first;


            int &status = stack.top().second;
            
            if(status == 0)
            {
                idx++;
                if(idx == word.size())
                    return true;
                visited[pos.first][pos.second] = true;
            }


            if(status != 4)
            {
                if(status == 0 && pos.first-1 >= 0 && visited[pos.first-1][pos.second]==false && board[pos.first-1][pos.second] == word[idx])
                {
                    stack.push(make_pair(make_pair(pos.first-1, pos.second), 0));
                }
                else if(status == 1 && pos.first+1 < board.size() && visited[pos.first+1][pos.second]==false && board[pos.first+1][pos.second] == word[idx])
                {
                    stack.push(make_pair(make_pair(pos.first+1, pos.second), 0));
                }
                else if(status == 2 && pos.second-1 >= 0 && visited[pos.first][pos.second-1]==false && board[pos.first][pos.second-1] == word[idx])
                {
                    stack.push(make_pair(make_pair(pos.first, pos.second-1), 0));
                }
                else if(status == 3 && pos.second+1 < board[0].size() && visited[pos.first][pos.second+1]==false && board[pos.first][pos.second+1] == word[idx])
                {
                    stack.push(make_pair(make_pair(pos.first, pos.second+1), 0));
                }
                status++;
            }
            else
            {
                visited[pos.first][pos.second] = false;
                stack.pop();
                idx--;
            }
        }
        return false;
    }
};





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值