根据数据范围,可以使用动态规划来优化搜索代码的时间复杂度。

首先,定义一个二维数组dp,dp[i][j]表示从起点(0,0)到达点(i,j)的路径数量。

然后,使用动态规划的方法填充dp数组。从起点(0,0)开始,依次计算每个位置的路径数量。对于每个位置(i,j),其路径数量等于上方位置(i-1,j)和左方位置(i,j-1)的路径数量之和。即dp[i][j] = dp[i-1][j] + dp[i][j-1]。

最后,输出dp[b_x][b_y]作为结果。

优化后的代码如下:

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
bool xy[35][35];
int dp[25][25];
int b_x,b_y;
int h_x,h_y;

int main(void){
    ios::sync_with_stdio(false);
    cin.tie(0);  cout.tie(0);
    cin>>b_x>>b_y>>h_x>>h_y;
    xy[h_x-1][h_y-2]=true;
    xy[h_x+1][h_y-2]=true;
    xy[h_x-2][h_y-1]=true;
    xy[h_x+2][h_y-1]=true;
    xy[h_x-2][h_y+1]=true;
    xy[h_x+2][h_y+1]=true;
    xy[h_x-1][h_y+2]=true;
    xy[h_x+1][h_y+2]=true;
    xy[h_x][h_y]=true;

    dp[0][0] = 1;
    for(int i=0;i<=b_x;i++){
        for(int j=0;j<=b_y;j++){
            if(i==0 && j==0) continue;
            if(xy[i][j]) dp[i][j] = 0;
            else{
                if(i==0) dp[i][j] = dp[i][j-1];
                else if(j==0) dp[i][j] = dp[i-1][j];
                else dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        }
    }
    cout<<dp[b_x][b_y];
    return 0;
}
``
对于 100 的数据1≤nm≤200≤ 马的坐标 ≤20。根据上述数据范围优化下方c++搜索代码的时间复杂度#includeiostream#includecstring#includealgorithmusing namespace std;bool xy3535;int sum;int b_xb_y;int h_xh_y;void dfsint xint y	ifxyx+1y&&xyxy+1

原文地址: http://www.cveoy.top/t/topic/iAoa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录