机器人的运动范围 剑指offer66题

本文介绍了一个算法问题:在给定阈值、行数和列数的情况下,计算矩阵中可移动的格子数量。通过递归遍历矩阵并利用回溯的方法,实现了对符合条件的格子计数。

include "stdafx.h"

#include<vector>
#include<algorithm>
#include<string>
#include<iostream>
#include<stack>
using namespace std;

class Solution {
public:
    int getSum(int rows, int cols)
    {
        int sum = 0;
        while (rows!=0)
        {
            sum += rows % 10;
            rows = rows / 10;
        }
        while (cols != 0)
        {
            sum += cols % 10;
            cols = cols / 10;
        }
        return sum;
    }
    int count = 0;
    int movingCount(int threshold, int rows, int cols)
    {
        vector<vector<bool>> visited(rows,vector<bool>(cols,false));
        getCount(threshold, 0, 0, visited, rows, cols);
        return count;
    }
    void getCount(int threshold, int rows, int cols, vector<vector<bool>> &visited,int m,int n)
    {
        if (getSum(rows, cols) <= threshold)
        {
            count++;
        //  cout << count << endl;
            visited[rows][cols] = true;
            if (cols - 1 >= 0&&visited[rows][cols-1]==false)
            {
                getCount(threshold, rows, cols - 1, visited,m,n);
            }
            if (cols + 1 < n && visited[rows][cols + 1]==false)
            {
                getCount(threshold, rows, cols + 1, visited,m,n);
            }
            if (rows - 1 >= 0 && visited[rows-1][cols]==false)
            {
                getCount(threshold, rows-1, cols , visited,m,n);
            }
            if (rows + 1 < m && visited[rows + 1][cols]==false)
            {
                getCount(threshold, rows + 1, cols, visited,m,n);
            }
        //  visited[rows][cols] = false;
            //count--;
            
        }
    

    }

};
int main()
{
    Solution s;
    cout << s.movingCount(5, 10, 10) << endl;

    return 0;
}

转载于:https://www.cnblogs.com/wdan2016/p/6858301.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值