AcWing 24. 机器人的运动范围(DFS+BFS)

【STC8G1K08A串口使用】 STC8G1K08A串口打印“Hello world” 阅读详情

1.DFS

从起点位置开始深入,遇到合法位置则计数器自增,否则返回。由于题目不需要回溯,因此访问数组不必还原。

具体代码如下:

class Solution {
public:
    int dx[2] = {0, 1}; //根据题意可以发现只需要有两个方向即可
    int dy[2] = {1, 0};
    
    //计算数位和
    int getSum(int x, int y){
        int t = 0;
        while(x){
            t += x % 10;
            x /= 10;
        }
        while(y){
            t += y % 10;
            y /= 10;
        }
        return t;
    }
    
    void dfs(vector<vector<int>> &visit, int x, int y, int &sum, int &th)
    {
        if(getSum(x, y) > th) return; //当前位置的坐标数位和大于阈值,故返回
        visit[x][y] = 1;
        sum++;
        for(int i = 0; i < 2; i++){
            int newx = x + dx[i], newy = y + dy[i];
            if(newx < visit.size() && newy < visit[0].size() && visit[newx][newy] == 0){
                dfs(visit, newx, newy, sum, th);
            }
        }
    }
    
    int movingCount(int threshold, int rows, int cols)
    {
        if(rows == 0) return 0;
        vector<vector<int>> visit(rows, vector<int> (cols, 0));
        int sum = 0;
        dfs(visit, 0, 0, sum, threshold);
        return sum;
    }
};

2.BFS

相比于AcWing 23. 矩阵中的路径(DFS),这道题就可以使用BFS求解。因为这道题不是对指定次序的序列进行查找判断,而是对单点进行查找判断。

具体代码如下:

class Solution {
public:
    int dx[2] = {0, 1}; //根据题意可以发现只需要有两个方向即可
    int dy[2] = {1, 0};
    
    //计算数位和
    int getSum(int x, int y){
        int t = 0;
        while(x){
            t += x % 10;
            x /= 10;
        }
        while(y){
            t += y % 10;
            y /= 10;
        }
        return t;
    }
    
    int movingCount(int threshold, int rows, int cols)
    {
        if(rows == 0) return 0;
        vector<vector<int>> visit(rows, vector<int> (cols, 0));
        queue<pair<int, int>> q;
        int sum = 0;
        q.push({0, 0}); //根据题意,起点一定满足条件,所以这里直接压入队列没做判断
        visit[0][0] = 1;
        while(!q.empty()){
            int x = q.front().first, y = q.front().second;
            q.pop();
            sum++;
            for(int i = 0; i < 2; i++){
                int newx = x + dx[i], newy = y + dy[i];
                if(newx >= rows || newy >= cols || getSum(newx, newy) > threshold || visit[newx][newy])
                    continue;
                q.push({newx, newy});
                visit[newx][newy] = 1;
            }
        }
        return sum;
    }
};

 

相关推荐

告别环境配置噩梦:用Docker Desktop + WSL2在Windows上5分钟搞定vLLM运行环境

本文详细介绍了如何在Windows系统上使用Docker Desktop和WSL2快速搭建vLLM开发环境,5分钟内完成配置。通过容器化技术解决传统环境配置中的依赖冲突、环境污染等问题,提供一键复用的高效方案,特别适合AI开发者快速部署和测试vLLM框架。

weixin_28728495的博客 502

acwing—845八数码的详细讲解【化简成迷宫来理解】

其实走迷宫和八数码是本质相同的题目,但之所以get不到是因为前者很容易想象出来,但后者的迷宫形式很抽象,那么我今天就将这两道题的本质挖出来,对比一下,想象部分人会豁然贯通的; 先放一下题目,这里为了减少文章的长度就直接放题目链接了; AcWing 845. 八数码 - AcWing 844. 走迷宫 - AcWing题库 先讲简单的走迷宫,我们先来确认一下对象有哪些,对象又有哪些属性; 对象——方形位置。 属性一:相对位置 因为每个方形都对其他方形有唯一的相对位置,虽然这个属性看起来很抽象,但

weixin_62953519的博客 966

【任何电机可使用的七段式s曲线-----包括matlab代码和simulink仿真】

S形加加速(T1)→>匀加速(T2)→减加速(T3)→>匀速(T4 )>加减速(T5)>匀减速(T6)-→>减减速(T7)

weixin_44312889的博客 6309

Acwing---24. 机器人的运动范围(Java)__DFS深搜

机器人的运动范围 ①. 题目②. 思路③. 学习点④. 代码实现 原题链接 ①. 题目 ②. 思路 DFS深搜全部节点,DFS套娃递归结束的条件就是行坐标和纵坐标的数位和相加大于K,开一个二维数组对访问的节点进行记录,上下左右四个方向搜索,再判断边界的时候还是判断是否访问过,还有下一个点的数位和是否满足,若满足则结果+1 ③. 学习点 DFS+记忆化 ④. 代码实现 import java.util.*; public class _24_机器人的范围_dfs { public stati

396

【NAS for PVE _04】安装TrueNAS

前篇说到如何调试 Proxmox VE 8.2 为安装虚拟机做准备,本篇主要讲述如何在 Proxmox VE 上安装 TrueNAS 系统,并开启NFS供其他系统挂载使用官网下载好TrueNAS系统镜像。

村口王师傅。 6144

手机相机基础技术解析:从硬件到算法的全面指南

手机相机的成像过程可简化为的链路,其核心硬件包括 镜头、CMOS传感器、ISP(图像信号处理器) 以及配套的软件算法。

weixin_44239603的博客 2448

AcWing 845. 八数码

在一个3×3的网格中,1~8这8个数字和一个“X”恰好不重不漏地分布在这3×3的网格中。 例如: 1 2 3 X 4 6 7 5 8 在游戏过程中,可以把“X”与其上、下、左、右四个方向之一的数字交换(如果存在)。 我们的目的是通过交换,使得网格变为如下排列(称为正确排列): 1 2 3 4 5 6 7 8 X 例如,示例中图形就可以通过让“X”先后与右、下、右三个方向的数字交换成功得到正确排列。...

Allen的博客 398

FPGA实现DDR接口

verilog// DDR2控制器状态机// 初始化序列// 发出初始化命令endendendend// 自动预充电end// 其他状态...endcaseendend。

whm128的博客 998

《剑指Offer》第12-22题

AcWing 24. 机器人的运动范围 地上有一个 m 行和 n 列的方格,横纵坐标范围分别是 0∼m−1 和 0∼n−1。 一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格。 但是不能进入行坐标和列坐标的数位之和大于 k 的格子。 请问该机器人能够达到多少个格子? 样例1 输入:k=7, m=4, n=5 输出:20 样例2 输入:k=18, m=40, n=40 输出:1484 解释:当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。 但是,它

pxlsdz的博客 1002

【腾讯小龙虾WorkBuddy专栏02】保姆级安装教程!彻底分清WorkBuddy/CodeBuddy,最新积分活动&会员体系全攻略

【腾讯小龙虾WorkBuddy专栏02】保姆级安装教程!彻底分清WorkBuddy/CodeBuddy,最新积分活动&会员体系全攻略

AI人人懂 2596

CATIA二次开发一一一获取属性的几种方法

这些方法覆盖了CATIA CAA开发中属性操作的典型场景,开发者可通过类型判断实现递归遍历、跨文档关联等复杂逻辑。此方法用于遍历对象的所有属性,获取属性键后可通过类型判断选择后续处理方式。适用于处理嵌套对象或关联对象的场景(如几何特征关联制造特征)。适用于简单属性值的直接读取(如版本号、状态标识等)。用于处理多值属性(如多选参数、装配体子件列表等)。用于处理跨文档引用(如零件关联图纸文件)。

工业软件开发 431

LeetCode笔记-机器人的运动范围( Python图解)

LeetCode笔记-机器人的运动范围,DFS / BFS ,清晰图解,Python语言实现

算法之美 1240

基于STM32的汽车主门电动窗开关系统设计方案

以下是基于 STM32CubeMX 和 HAL 库的示例代码,可实现基本的功能。

weixin_42300449的博客 995

剑指Offer打卡day8—— AcWing 24. 机器人的运动范围

【题目描述】 AcWing 24. 机器人的运动范围 DFS 【思路】 遍历每一个合法位置 class Solution { int ans = 0; int [][] dir = new int[][]{{-1, 0}, {0, 1}, {1, 0}, {0, - 1}}; public int get_single_sum(int x){ int res = 0; while(x > 0){ res = r

JohnnyLin 142

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

AcWing 24:机器人的运动范围 ← BFS、DFS

地上有一个 m 行和 n 列的方格,横纵坐标范围分别是 0∼m−1 和 0∼n−1。 一个机器人从坐标 (0,0) 的格子开始移动,每一次只能向左,右,上,下四个方向移动一格。 但是不能进入行坐标和列坐标的数位之和大于 k 的格子。 请依次输入k,m,n,问该机器人能够达到多少个格子? 注意:0

hnjzsyjyj的专栏 1245

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

AcWing 24. 机器人的运动范围(BFS和DFS)

AcWing 24. 机器人的运动范围 分析 这题是一道非常经典可以使用BFS也可以DFS的搜索题,题干有四连通。 ①先做好一些初始工作:初始化队列、初始化记录状态的数组、初始化四连通数组 ②接着就让队列一直循环 2.1 先从队列取值,再去掉队头 2.2 判断是否满足条件,若不满足就下一次循环 2.3 满足条件了,那就做题目中要求做的事。这题是要找能到达点有多少, 然后还要刷新状态 2.4 从中心点向四周扩散(四连通、八连通) 代码 bfs class Solution { public: int

Alphacoo的博客 201

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

ACWING24. 机器人的运动范围(搜索,剑指offer)

地上有一个 m 行和 n 列的方格,横纵坐标范围分别是 0∼m−1 和 0∼n−1。 一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格。 但是不能进入行坐标和列坐标的数位之和大于 k 的格子。 请问该机器人能够达到多少个格子? 样例1 输入:k=7, m=4, n=5 输出:20 样例2 输入:k=18, m=40, n=40 输出:1484 解释:当k为18时,机...

tomjobs的博客 341

AcWing解题目录(C++)

# 试题名称 思想方法 难度 试题来源 1 A+B 简单 AcWing 2 01背包问题 简单 3 完全背包问题 简单 4 多重背包问题I 简单 5 多重背包问题II 中等 6 多重背包问题...

Zee_Chao的博客 900

算法唯手熟尔4月(PAT剩余清单 or leetcode)---希望可以日更

文章目录2020/4/1leetcode 914. 卡牌分组_Goleetcode 1111. 有效括号的嵌套深度_Go2020/4/2leetcode 289. 生命游戏_Go2020/4/3leetcode 8. 字符串转换整数_Go2020/4/4leetcode 42. 接雨水_Go2020/4/5leetcode 460. LFU缓存_Go2020/4/6leetcode 1013. 将...

qq_42192672的博客 961

【算法基础】BFS 广度优先搜索——AcWing 844. 走迷宫 AcWing 845. 八数码 题解

AcWing 844. 走迷宫 AcWing 845. 八数码 题解

Remember who you are! 2936

24. 机器人的运动范围

地上有一个mm行和nn列的方格,横纵坐标范围分别是0∼m−10∼m−1和0∼n−10∼n−1。 一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格。 但是不能进入行坐标和列坐标的数位之和大于kk的格子。 请问该机器人能够达到多少个格子? 样例1 输入:k=7, m=4, n=5 输出:20 样例2 输入:k=18, ...

371

BFS、DFS——机器人的运动范围

题目描述 地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子? public class Sol

jingsuwen1的博客 3920

AcWing 24. 机器人的运动范围

题目描述 地上有一个m行和n列的方格,横纵坐标范围分别是0∼m−1和0∼n−1。 一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格。 但是不能进入行坐标和列坐标的数位之和大于k的格子。 请问该机器人能够达到多少个格子? 样例1 输入:k=7, m=4, n=5 输出:20 样例2 输入:k=18, m=40, n=40 输...

yj_coder的博客 199

ACwing 24. 机器人的运动范围

class Solution { public: typedef pair<int,int>PII; int get_single_sum(int x) { int s=0; while(x)s+=x%10,x/=10;//求下标和 return s; } int get_sum(PII p) { ...

qtmatt的博客 213

机器人的运动范围(DFS)

题目描述 地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子? DFS实现,不需要回溯,

You_are_my_dream的博客 597

更新sql的执行过程

数据库的查询操作具有天然幂等性,不会对数据库有任何的修改。但是mysql如何实现对数据库的更新操作呢?

行而不辍,未来可期 - King 4155
上一篇: 912数据结构自学习题总结Part1
下一篇: 912数据结构自学习题目录
Zee_Chao
博客等级 码龄11年 168粉丝 135原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值