目录
第一题-解读密码
思路:
接收整个数组之后,判断是否是数字,如果是数字则输出
// 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;
}