目录
第一题-迷宫问题
思路:
首先将所有的数组存放到maze中,然后从左上角开始寻找走过的地方标志为1,并且将走过的路径存放到tmp中,之后判断如果走到头了,则将tmp给best,没有到头就上下左右走,直到遇到1开始回溯
#include<iostream>
#include<vector>
using namespace std;
int row,col;
vector<vector<int>> maze;//存放迷宫
vector<vector<int>> push_tmp;//临时路径
vector<vector<int>> push_best;//最佳路径
void maze_get(int i, int j)
{
//给1表示走过了
maze[i][j] = 1;
push_tmp.push_back({i,j});
//判断是不是走到头了
if(i == row-1 && j == col-1)
{
//如果best为空或者best长度比tmp长,将tmp赋值给best
if(push_best.empty() || push_best.size() > push_tmp.size())
{
push_best = push_tmp;
}
}
//向左走
if(j-1 >= 0 && maze[i][j-1] == 0)
{
maze_get(i, j-1);
}
//向右走
if(j+1<col && maze[i][j+1] == 0)
{
maze_get(i, j+1);
}
//向上走
if(i-1 >= 0 && maze[i-1][j] == 0)
{
maze_get(i-1, i);
}
//向下走
if(i+1 < row && maze[i+1][j] == 0)
{
maze_get(i+1, j);
}
//回溯
maze[i][j] = 0;
push_tmp.pop_back();
}
int main ()
{
while(cin>>row>>col)
{
//将maze空间初始化为0
maze = vector<vector<int>>(row, vector<int>(col, 0));
//清除上一组的数据
push_tmp.clear();
push_best.clear();
//将数据存放到maze中
for(int i = 0; i < row; ++i)
{
for(int j = 0; j < col; ++j)
{
cin>>maze[i][j];
}
}
//起始位置是(0, 0)
maze_get(0, 0);
for(int i = 0; i < push_best.size(); ++i)
cout<<"("<<push_best[i][0]<<","<<push_best[i][1]<<")"<<endl;
}
return 0;
}
第二题-年终奖
思路:
动态规划解决问题,每次移动都和上一次的价值比较,将上一次最大值和本格棋盘最大值相加
class Bonus {
public:
int getMost(vector<vector<int> > board) {
int row = board.size();
int col = board[0].size();
vector<vector<int>> price(row, vector<int>(col, 0));//存放价值
price[0][0] = board[0][0];
for(int i = 0; i < row; ++i)
{
for(int j = 0; j < col; ++j)
{
//跳过第一个点
if(i == 0 && j == 0)
{
continue;
}
//在第一行中,当前价值等于上一行价值加上本格棋盘价值
else if(i == 0)
{
price[i][j] = price[i][j-1] + board[i][j];
}
//在第一列中,当前价值等于上一列价值加上本格棋盘价值
else if(j == 0)
{
price[i][j] = price[i-1][j] + board[i][j];
}
//当前价值等于当前本格棋盘价值加上上一行和上一列中的较大值
else
{
price[i][j] = max(price[i-1][j], price[i][j-1]) + board[i][j];
}
}
}
return price[row-1][col-1];
}
};