骑士周游 贪心优化

思路:在原本直接回溯版本的基础上,走下一步的时候考虑下一步的下一步可行解的数量,按可行解的数量从小到大的顺序选择下一步。优化出来的效率高很多,再次感受到算法的魅力。

/*输入n*n的棋盘,输出从给定位置出发的马踏棋盘的路径*/
#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
#define debug cout<<"debug___________"<<endl
using namespace std;
const int maxn=100;
int chess[maxn][maxn];
int sx,sy;
int n;
int dirx[]={-2,-1,1,2,2,1,-1,-2};
int diry[]={1,2,2,1,-1,-2,-2,-1};

struct Step{
    int dir,cnt;
};

bool cmp(Step a,Step b){
    return a.cnt<b.cnt;
}

bool judge(int x,int y){
    return (x>=1&&x<=n)&&(y>=1&&y<=n);
}

bool dfs(int x,int y,int depth){
    if(depth==n*n){debug;debug;
        return true;
    }
    Step ok[8];
    memset(ok,0,sizeof(ok));
    for(int i=0;i<8;i++){
        int next_x=x+dirx[i];
        int next_y=y+diry[i];
        if(!judge(next_x,next_y)||chess[next_x][next_y]) continue;
        if(depth==n*n-1){
            chess[next_x][next_y]=depth+1;
            return true;
        }
        for(int j=0;j<8;j++){
            int next_next_x=next_x+dirx[j];
            int next_next_y=next_y+diry[j];
            if(!chess[next_next_x][next_next_y]&&judge(next_next_x,next_next_y)){
                ok[i].cnt++;
                ok[i].dir=i;
            }
        }
    }
    int temp_x,temp_y;
    sort(ok,ok+8,cmp);
    int i;
    for(i=0;i<8;i++){
        if(ok[i].cnt){
            temp_x=x+dirx[ok[i].dir];
            temp_y=y+diry[ok[i].dir];
            if(!chess[temp_x][temp_y]){
                chess[temp_x][temp_y]=depth+1;
                if(dfs(temp_x,temp_y,depth+1)) break;
                chess[temp_x][temp_y]=0;
            }
        }
    }
    if(i==8) return false;
    return true;
}

int main(){
    while(scanf("%d",&n)!=EOF){
        if(n<6){
            printf("erro\n");
            continue;
        }
        memset(chess,0,sizeof(chess));
        scanf("%d%d",&sx,&sy);
        chess[sx][sy]=1;
        if(dfs(sx,sy,1)){
            for(int i=1;i<=n;i++){
                for(int j=1;j<=n;j++)
                    printf("%3d%c",chess[i][j],j==n?'\n':' ');
            }
        }
        else
            printf("No solution\n");
    }
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值