leetcode

给定一个字符表和一个字符串,判断能否用相邻的字符连接起来形成该字符串。

算法

对每个表中的字符进行一遍DFS。在每次DFS的过程中,记录当前访问过的节点,以免重复访问。若能找到则返回true;否则返回false。

Code

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        int nowpos = 0, rows = board.size(), cols = board[0].size(), wsize=word.size();
        for (int i = 0; i < rows; i++){
            for (int j = 0; j < cols; j++){
                vector<vector<bool>> passed(rows, vector<bool>(cols, false));
                if(dfsrecurtive(board, i, j, rows, cols, nowpos, word, passed,wsize)==wsize) return true;
            }
        }
        return false;
    }

    int dfsrecurtive(vector<vector<char>> &board, int row, int col, int rows, int cols, int nowpos, 
        string& word, vector<vector<bool>>& passed, int wsize){

        if(board[row][col]!=word[nowpos]) return -1;
        if(board[row][col]==word[nowpos]) nowpos++;

        if(nowpos==wsize) return nowpos;

        for(auto d: dr){
            int newrow = row + d[0], newcol = col + d[1];
            if(newrow<0||newrow>=rows||newcol<0||newcol>=cols||passed[newrow][newcol]) continue;
            passed[row][col] = true;
            if(dfsrecurtive(board, newrow, newcol, rows, cols, nowpos, word, passed,wsize)==wsize) return wsize;
            passed[row][col] = false;
        }
        return -1;
    }

  private:
    vector<vector<int>> dr{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; //代表四个方向,左上右下
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值