P1002 过河卒:图论动态规划入门-代码:

时间:2024-04-03 06:55:48

  ac代码:

#include<iostream>
#include<cmath>
#include<vector>
using namespace std;

int n,m,a,b;//(m,n)是目标点,(a,b)是马
//马的路
int dx[8] = {-1,-2,-2,-1,1,2,2,1};
int dy[8] = {-2,-1,1,2,-2,-1,1,2};
const int N = 30;
int limit[N][N];
long long f[N][N];


int main(){
   cin >> n >> m >> a >> b;
    limit[a][b] = true;
    for(int i = 0;i < 8;i++){
        limit[a + dx[i]][b + dy[i]] = true;
    }
    
    f[0][0] = 1;
    for(int i = 0;i <= n;i++){
        for(int j = 0;j <= m;j++){
            if(!limit[i][j]){
                if(i) f[i][j] += f[i-1][j];
                if(j) f[i][j] += f[i][j-1];
            }
        }
    }
    
    cout << f[n][m];
    
    return 0;
}

在贴一个dfs的代码,过了40/100,其他的超时了

#include<iostream>
#include<cmath>
#include<vector>
using namespace std;

int n,m,a,b;//(m,n)是目标点,(a,b)是马
//马的路
int dx[8] = {-1,-2,-2,-1,1,2,2,1};
int dy[8] = {-2,-1,1,2,-2,-1,1,2};
const int N = 22;
int mp[N][N];
int limit[N][N];
int res = 0;
int dn[2] = {1,0};
int dm[2] = {0,1};

int charge(int x,int y){
    if(x < 0 || x > n || y < 0 || y > m) return false;
    return true;
}

void dfs(int x,int y){
    if(x == n && y == m){
        res ++;
        return;
    }
    
    for(int i = 0;i < 2;i++){
        int nowx = x + dn[i],nowy = y + dm[i];
        if(charge(nowx,nowy) && !limit[nowx][nowy]){
            dfs(nowx,nowy);
        }
    }
}

int main(){
   cin >> n >> m >> a >> b;
    limit[a][b] = true;
    for(int i = 0;i < 8;i++){
        limit[a + dx[i]][b + dy[i]] = true;
    }
    
    dfs(0,0);
    
    cout << res;
    
    return 0;
}

以上是本文全部内容,如果对你有帮助点个赞再走吧~  ₍˄·͈༝·͈˄*₎◞ ̑̑