N*N棋盘的非递归算法

#include <stdio.h>
#include <memory.h>

int table[] =
{
    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73,
    79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163,
    167, 173, 179, 181, 191, 193, 197, 199
};

char isPrime[] =
{
    0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0,
    0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1,
    0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1,
    0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0,
    1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0,
    0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0,
    0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1
};

int find(int N, int* pos, int curr_pos)
{
    int a, b, i, j, temp;
    int curr_value = 1, start;
    int stack[100], sp = 1;
    stack[0] = 0;
    start = 0;
    while(1){
        a = curr_pos / N; b = curr_pos % N;
        for(i = start; i < 46; i++){
            if(b == 0){
                if(a == 0) temp = curr_value;
                else temp = table[i] - pos[(a-1)*N];
            }else if(a == 0){
                temp = table[i] - pos[curr_pos-1];
            }else{
                temp = table[i] - pos[(a-1)*N+b];
                if(temp + pos[curr_pos-1] > 200 ||
                    !isPrime[temp + pos[curr_pos-1]]) continue;
            }
            if(temp < 1) continue;
            if(temp > N*N) break;
            for(j = 0; j < curr_pos; j++)
                if(temp == pos[j]) break;
            if(j == curr_pos) break;
        }
        if(i != 46 && temp <= N*N){
            pos[curr_pos++] = temp;
            if(curr_pos == N*N) return 1;
            stack[sp++] = i;
            start = 0;
        }else{
            curr_pos--;
            if(curr_pos < 0) return 0;
            sp--;
            start = stack[sp]+1;
        }
    }
}

int main(int argc, char* argv[])
{
    int pos[10 * 10];

    int N, count, i, j, k;

    scanf("%d", &count);
    for(k = 0; k < count; k++){
        scanf("%d", &N);

        if(find(N, pos, 0)){
            for(i = 0; i < N; i++){
                for(j = 0; j < N; j++){
                    if(j == 0) printf("%d", pos[i*N+j]);
                    else printf(" %d", pos[i*N+j]);
                }
                putchar('/n');
            }
        }else puts("NO");
    }

    return 0;
}

Memory: 36K
Time: 2878ms

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值