判断回溯法中的标记数组vis在回溯的时候是否要取消标记?

  • 给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
class Solution {
    int dr[4] = {1, 0, -1, 0};
    int dc[4] = {0, -1, 0, 1};
public:
    bool exist(vector<vector<char>>& board, string word) {
        int n = board.size(), m = board[0].size();
        vector<vector<int>> vis(n, vector<int>(m, 0));
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                if(dfs(board, word, vis, i, j)) return true;
            }
        }
        return false;
    }
    bool dfs(vector<vector<char>>& board, string word, vector<vector<int>>& vis, int r, int c) {
        //cout << r << " " << c << " " << word << endl;
        if(word.size() == 0) return true;
        if(r < 0 || r >= board.size() || c < 0 || c >= board[0].size()) return false;
        if(vis[r][c]) return false;
        if(word[0] != board[r][c]) return false;
 
        vis[r][c] = 1;
        for(int i = 0; i < 4; i++) {
            if(dfs(board, word.substr(1), vis, r + dr[i], c + dc[i])) return true;
        }
        vis[r][c] = 0;                    // 回溯的时候标记要取消
        return false;
    }
};

 

  • 地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?
 
class Solution {
    int dr[4] = {1, 0, -1, 0};
    int dc[4] = {0, -1, 0, 1};
public:
    int movingCount(int m, int n, int k) {
        vector<vector<int>> vis(m, vector<int>(n, 0));
        return moving(m, n, k, 0, 0, vis);
    }
    int moving(int m, int n, int k, int r, int c, vector<vector<int>>& vis) {
        if(r < 0 || r >= m || c < 0 || c >= n) return 0;
        if(getNum(r, c) > k) return 0;
        if(vis[r][c]) return 0;
 
 
        vis[r][c] = 1;
        int ans = 1;
        for(int i = 0; i < 4; i++) {
            ans += moving(m, n, k, r + dr[i], c + dc[i], vis);
        }
        //vis[r][c] = 0;                   // 回溯的时候不能取消标记
        //cout << r << " " << c << " " << ans << endl;
        return ans;
    }
    int getNum(int r, int c) {
        int ans = 0;
        while(r) {
            ans += (r % 10);
            r /= 10;
        }
        while(c) {
            ans += (c % 10);
            c /= 10;
        }
        return ans;
    }
};

  

在12题中因为是要找到单词路径是否存在,如果到达二维矩阵中某个位置因不满足条件需要回溯,则在找下一个可能的路径的时候该位置仍然是可以访问的。因此在回溯的时候vis标记要取消。
在13题中因为是求可达到的格子总和,所以只要某个格子被访问后就不能再次访问了,否则可能会有重复计算。因此在回溯的时候vis标记要取消。
 
综上,判断在回溯时vis标记是否需要取消,要根据回溯后该格子是否还能被之后其他方式/路径访问决定。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
posted @ 2021-08-09 21:00  萌新的学习之路  阅读(94)  评论(0编辑  收藏  举报