笔试强训day42(解读密码, 走迷宫)

目录

第一题-解读密码

第二题-走迷宫


第一题-解读密码

思路:

        接收整个数组之后,判断是否是数字,如果是数字则输出

// write your code here cpp
#include<iostream>
using namespace std;
int main ()
{
    string s;
    while(getline(cin, s))
    {
        for(auto ch : s)
        {
            if(isdigit(ch))
                cout<<ch;
        }
        cout<<endl;
    }
    return 0;
}

第二题-走迷宫

思路:

        用ans记录最短路径需要走的步数,cur存放临时路径走的步数,当超出范围或者没有遇到"."就结束,否则,剪枝,防止多余计算,之后比较当前路径和最短路径,只有将当前位置标记为"#"之后dfs下一个位置,回来的时候将原来的位置标记为"."

#include <iostream>
#include <vector>
#include <string>
#include <limits.h>
using namespace std;

//ans存放最短路径,cur存放当前路径
void FindLeastSteps(vector<string>& maze, int x, int y, int& ans, int cur)
{
	if (x > 9 || y > 9 || x < 0 || y < 0 || maze[x][y] != '.')
		return;
    //这个地方的剪枝防止多余的计算
    if(cur > ans)
        return;
    //存储最短路径
	if (x == 9 && y == 8)
	{
		if (ans > cur)
			ans = cur;
		return;
	}
    
    //我们将x,y走过的路径的位置变为'#',
    //这样就不用再开辟一个额外的used数组去记录已经走的路了
	maze[x][y] = '#';

	FindLeastSteps(maze, x, y + 1, ans, cur + 1);
	FindLeastSteps(maze, x + 1, y, ans, cur + 1);
	FindLeastSteps(maze, x, y - 1, ans, cur + 1);
	FindLeastSteps(maze, x - 1, y, ans, cur + 1);
    
    //回到上层递归时,要把当前所在位置重新设为'.' 代表没走这个位置
	maze[x][y] = '.';
}

int main()
{
    vector<string> maze(10);
	while (cin>>maze[0])
	{
        for(int i = 1; i < 10; ++i)
        {
            cin>>maze[i];
        }
        int ans = INT_MAX;
        FindLeastSteps(maze, 0, 1, ans, 0);
        cout << ans << endl;
	}
	return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

penguin_bark

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值