算法和数据操作篇——回溯法

面试题12:矩阵中的路径原题链接

class Solution {
public:
    bool has_word(int x, int y, vector<vector<char>>& board, string& word, int index, vector<vector<int>>& mark){
    	// 从board[x][y]出发,寻找word[index],mark矩阵表示某个位置的字符是否已经被使用
        int n = board.size(), m = board[0].size();
        int dx[4] = {0, 1, -1, 0};
        int dy[4] = {-1, 0, 0, 1};
        if(index == word.size())
            return true;
        
        mark[x][y] = 1;    // 当前的位置已经不再可用
        for(int i = 0;i < 4; i++){
            int nx = x + dx[i], ny = y + dy[i];
            if(nx >= 0 && nx < n && ny >= 0 && ny < m && mark[nx][ny] == 0 && board[nx][ny] == word[index]){
                if(has_word(nx, ny, board, word, index+1, mark))
                    return true;
            }
        }
        // 上面的循环体中如果找到了index后面的所有字符,就会返回true,如果没有,则需要在返回时将mark的状态修改回去
        mark[x][y] = 0;
        
        return false;
    }
    bool exist(vector<vector<char>>& board, string word) {
        int n = board.size();
        if(n == 0)
            return word.size() == 0;
        if(word.size() == 0)
            return true;
        int m = board[0].size();
        // 标记矩阵中的字符是否已经被遍历过
        vector<vector<int> > mark(n, vector<int>(m, 0));

        for(int i = 0;i < n; i++){
            for(int j = 0;j < m; j++){
                if(board[i][j] == word[0]){
                    if(has_word(i, j, board, word, 1, mark))
                        return true;
                }
            }
        }
        return false;
    }
};

面试题13:机器人的运动范围原题链接

class Solution {
public:
    int dfs(int x, int y, int m, int n, int k, vector<vector<int> >& visited){
        int dx[4] = {0, 0, 1, -1};
        int dy[4] = {1, -1, 0, 0};
        int nx, ny, ans = 1;
        visited[x][y] = 1;
        for(int i = 0;i < 4; i++){
            nx = x + dx[i];
            ny = y + dy[i];
            if(nx >= 0 && nx < m && ny >= 0 && ny < n && visited[nx][ny] == 0 && check(nx, ny, k))
                ans += dfs(nx, ny, m, n, k, visited);
        }
        return ans;
    }
    bool check(int x, int y, int k){
        int ans = 0;
        while(x >= 1){
            ans += x % 10;
            x /= 10;
        }
        while(y >= 1){
            ans += y % 10;
            y /= 10;
        }
        return ans <= k;
    }
    int movingCount(int m, int n, int k) {
        vector<vector<int> > visited(m, vector<int>(n, 0));
        return dfs(0, 0, m, n, k, visited);
    }
};

你可能感兴趣的:(剑指offer(C++))