LeetCodes——79. Word Search【DFS】

题目要求

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 =
[
[‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’]
]
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.
给定一个二维字符数组和一个字符串,判断字符串能不能通过在二维数组中沿着水平和垂直两种方向拼出来,同一个位置上的字符只能用一次,如果可以则返回TRUE,不能则返回false。

解题思路

这又是一个典型的深搜,用两层for循环,去找寻入口,若找到满足条件的入口(board[i][j] = word[0]),则在board[i][j]的四周找寻满足条件的下一个字符。注意,同一个位置上的字符只能用一次,因此,需要一个visited数组来保存二维数组的访问状态。

代码

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        int m = board.size();
        int n = board[0].size();
        if (m == 0 || n == 0){
            return false;
        }
        for (int i=0;i<m;i++){
            for (int j=0;j<n;j++){
                vector<vector<bool>> visited(m,vector<bool>(n,false));
                if (dfs(board,i,j,word,visited) == true){//如果找到,则返回TRUE。
                    return true;
                }
            }
        }
        return false;
    }
    bool dfs(vector<vector<char>>& board, int i, int j, string word, vector<vector<bool>> & visited){
        if (word.length() == 0){//找到,匹配成功
            return true;
        }
        if (!(i>=0 && i<board.size()) || !(j>=0 && j<board[0].size())){
            return false;
        }
        if (board[i][j] != word[0]){
            return false;
        }
        else if (visited[i][j] == false){
            visited[i][j] = true;
            bool res;
            res = dfs(board,i+1,j,word.substr(1),visited);//在i,j的上下左右找寻。
            if (!res) res = dfs(board,i-1,j,word.substr(1),visited);
            if (!res) res = dfs(board,i,j-1,word.substr(1),visited);
            if (!res) res = dfs(board,i,j+1,word.substr(1),visited);
            if (res){
                return res;
            }else{
                visited[i][j] = false;
                return res;
            }
        }else{
            return false;
        }
    }
};

结果

87 / 87 test cases passed.
Status: Accepted
Runtime: 868 ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值