剑指 Offer 12. 矩阵中的路径

剑指 Offer 12. 矩阵中的路径

原题

剑指 Offer 12. 矩阵中的路径

思路

这个题主要是DFS,注意边界判断

代码

class Solution {
public:
    int xIndex[4] = {-1, 0, 0, 1};
    int yIndex[4] = {0, -1, 1, 0};
    bool exist(vector<vector<char>>& board, string word) {
        int m = board.size(), n = board[0].size();
        vector<vector<bool>> visit(m, vector<bool> (n));
        for (int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++){
               bool ans = dfs(visit, board, word, 0, i, j);
               if (ans) return true;
            } 
        }
        return false;
    }
    bool dfs(vector<vector<bool>>& visit, vector<vector<char>>& board, string word, int nowIndex, int x, int y){
        if (board[x][y] != word[nowIndex]) return false;
     	else if (nowIndex == word.length()-1) {
            return true;
        } 
        visit[x][y] = true;
        bool result = false;
        for (int i = 0; i < 4; i++){
            if(x+xIndex[i] >= 0 && x+xIndex[i] < board.size() && y+yIndex[i] >=0 && y+yIndex[i] < board[0].size()) {
                if(!visit[x+xIndex[i]][y+yIndex[i]] ) {
                    bool flag = dfs(visit, board, word, nowIndex+1, x+xIndex[i], y+yIndex[i]);
                    if (flag) {
                    	result = true;
                     	break;
			    	}
                } 
            }
        }
        visit[x][y] = false;
        return result; 
    }
};

运行截图

在这里插入图片描述

收获

  • DFS题一定要注意边界条件和判断条件
  • 判断条件一般放进dfs函数里,第一个判断最好也放进去
  • dfs一般的模板:
 bool  dfs(参数) {
      if 不满足条件 : return false;
      else if 满足: return true;
      visited[i]=true;
      bool result=dfs(next);
      visited[i]=false;
      return result;
   }
   
  • 二维动态数组可以这样初始化:vector<vector<int>> visited(m, vector<int> (n));
  • 方向可以用pair这么写:
 vector<pair<int, int>> directions{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

使用的时候:

for (auto dir:directions ) {
    newi = i + dir.first; newj = j + dir.second;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值