49. 跳馬問題


49. 跳馬問題

★   輸入文件:horse.in   輸出文件:horse.out   簡單對比
時間限制:1 s   內存限制:128 MB

【問題描述】

    有一只中國象棋中的 “ 馬 ” ,在半張棋盤的左上角出發,向右下角跳去。規定只許向右跳(可上,可下, 但不允許向左跳)。請編程求從起點 A(1,1) 到終點 B(m,n) 共有多少種不同跳法。

 
 【輸入格式】
 
    輸入文件只有一行,兩個整數m和n(1≤m,n≤20),兩個數之間有一個空格。
 【輸出格式】
 
    輸出文件只有一個整數,即從 A 到 B 全部的走法。
 
 【輸入輸出樣例】
 
   輸入文件(horse.in)
   5 9
 
  輸出文件(horse.out)
   37
思路:寬搜
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n,m,ans;
int vis[110][110];
struct nond{
    int x,y;
};
queue<nond>que;
int dx[5]={2,-2,1,-1};
int dy[5]={1,1,2,2};
int main(){
    freopen("horse.in","r",stdin);
    freopen("horse.out","w",stdout);
    scanf("%d%d",&n,&m);
    nond be;
    be.x=1;be.y=1;
    que.push(be);
    while(!que.empty()){
        nond now=que.front();
        que.pop();
        for(int i=0;i<4;i++){
            int cx=now.x+dx[i];
            int cy=now.y+dy[i];
            if(cx==n&&cy==m)    ans++;
            else if(cx>=1&&cx<=n&&cy>=1&&cy<=m){
                nond cc;
                cc.x=cx;
                cc.y=cy;
                que.push(cc);
            }
        }
    }
    printf("%d",ans);
}

 

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int f[21][21];
int n,m,ans;
int dfs(int x,int y){
    if(x<1||x>n||y<1||y>m)    return 0;
    if(f[x][y])    return f[x][y];
    return f[x][y]+=(dfs(x-1,y-2)+dfs(x-2,y-1)+dfs(x+1,y-2)+dfs(x+2,y-1));
}
int main(){
    freopen("horse.in","r",stdin);
    freopen("horse.out","w",stdout);
    scanf("%d%d",&n,&m);
    f[1][1]=1;
    dfs(n,m);
    cout<<f[n][m];
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM