刚做出来,好气哦,不确定对不对,欢迎大家纠错~~
题目大概是输入 n行m列,起始点sx,sy,求能到达的最大数字。只能往比自己大的方向走。
#include <iostream>
#include<vector>
using namespace std;
int n,m,sx,sy;
void until_ismax(int i,int j,vector<vector<int> > vec,vector<vector<int> >& maxh,vector<vector<bool> >& ismax){
//四周都比它小 不能走
if(ismax[i][j]==true)
return;
//对上下左右递归 求从i j能到达的最大数字 直到走到最大数字的位置
if(i!=0&&vec[i][j]<vec[i-1][j]){
until_ismax(i-1,j,vec,maxh,ismax);
maxh[i][j]=max(maxh[i][j],vec[i-1][j]);
}
if(i!=n-1&&vec[i][j]<vec[i+1][j]){
until_ismax(i+1,j,vec,maxh,ismax);
maxh[i][j]=max(maxh[i][j],vec[i+1][j]);
}
if(j!=0&&vec[i][j]<vec[i][j-1]){
until_ismax(i,j-1,vec,maxh,ismax);
maxh[i][j]=max(maxh[i][j],vec[i][j-1]);
}
if(j!=m-1&&vec[i][j]<vec[i][j+1]){
until_ismax(i,j+1,vec,maxh,ismax);
maxh[i][j]=max(maxh[i][j],vec[i][j+1]);
}
//i j的最大数字求出后,若四周可达i j,则更新四周的最大数字为i j的最大可达数字
if(i!=0&&vec[i][j]>vec[i-1][j]){
maxh[i-1][j]=maxh[i][j];
}
if(i!=n-1&&vec[i][j]>vec[i+1][j]){
maxh[i+1][j]=maxh[i][j];
}
if(j!=0&&vec[i][j]>vec[i][j-1]){
maxh[i][j-1]=maxh[i][j];
}
if(j!=m-1&&vec[i][j]>vec[i][j+1]){
maxh[i][j+1]=maxh[i][j];
}
}
int main(){
//input
cin>>n>>m>>sx>>sy;
vector<vector<int> > vec(n,vector<int>(m,0));
vector<vector<int> > maxh(n,vector<int>(m,0));
vector<vector<bool> > ismax(n,vector<bool>(m,false));
for(int i=0;i<n;++i){
for(int j=0;j<m;++j){
cin>>vec[i][j];
maxh[i][j]=vec[i][j];
}
}
//init ismax as stop contidion
for(int i=0;i<n;++i){
for(int j=0;j<m;++j){
bool left,right,up,down=false;
if(i==0) up=true;
else up=vec[i][j]>vec[i-1][j];
if(i==n-1) down=true;
else down=vec[i][j]>vec[i+1][j];
if(j==0) left=true;
else left=vec[i][j]>vec[i][j-1];
if(j==m-1) right=true;
else right=vec[i][j]>vec[i][j+1];
if(left&&right&&up&&down) ismax[i][j]=true;
}
}
until_ismax(sx,sy,vec,maxh,ismax);
cout<<maxh[sx][sy];
return 0;
}