c - 8 张皇后对角线检查

标签 c n-queens

目前我正在创建一个程序,要求用户为 8 个皇后问题放置皇后。现在我几乎已经创建了程序,但我一直在思考如何使程序对角线检查。

这是(未完成的)代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int check_r_c(int**chess,int*p,int N,int M)
{
    int times=0;
    for(int i=0; i<N; i++)
    {
        times=0;
        for(int j=0; j<M; j++)
        {
            if(chess[i][j] == 1)
                times++;

        }
        if( times != 1)
        {
            *p=1;
            return 1;
        }
    }
    for(int j=0; j<M; j++)
    {
        times=0;
        for(int i=0; i<N; i++)
        {
            if(chess[i][j] == 1)
                times++;
        }
        if( times != 1)
        {
            *p=1;
            return 1;
        }
    }
    *p=0;
    return 0;
}
int main()
{
    int N,M;
    printf("Give the number of rows: \n");
    scanf("%d",&N);
    printf("Give the number of columns: \n");
    scanf("%d",&M);
    int**chess = malloc(N*sizeof(int));
    int i,j,ch;
    int*ptr;
    ptr=&ch;
    if(chess==NULL)
    {
        printf("\nMemory cannot be allocated\n");
        return 1;
    }
    for(i=0; i<N; i++)
    {
        if((chess[i] = malloc(M*sizeof(int)))==NULL)
        {
            printf("\nMemory cannot be allocated\n");
            return 1;
        }
    }
    for(int i=0; i<N; i++)
        for(int j=0; j<M; j++)
            chess[i][j]= 0;
    for(int k=0; k<N; k++)
    {
        printf("Give the position of the %d queen\n",k+1);
        scanf("%d",&i);
        scanf("%d",&j);
        if(chess[i][j] == 1)
        {
            printf("You cant put 2 queens in the same place!!!\n" );
            return 0;
        }
        chess[i][j] = 1;
    }
    check_r_c(chess,ptr,N,M);
    if(ch == 0)
        printf("Solution is correct!");
    else
        printf("Solution is incorrect!");
    for(int i=0; i<N; i++)
        free(chess[i]);
    free(chess);
}

最佳答案

检查对角线是否有皇后放置的逻辑是 (p,q) 是检查所有 i 位于 (p+i,q+i) 的所有位置,其中 p+i 和 q+i 都是董事会内。对于负数,使用 (p-i,q-i)。

关于c - 8 张皇后对角线检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47972901/

相关文章:

c - sscanf : Get a pointer to end position

java - ArrayList 无法正确保存对象(N Queens 示例)

c++ - 回溯N皇后算法

java - 斜查n皇后JAVA

链接静态库时编译 CUDA 代码

c - 在运行时从父终端临时禁用子进程

c - RecursiveFree 函数 - 警告 : initialization from incompatible pointer type [-Wincompatible-pointer-types]

java - 使用回溯递归的 8 皇后问题

java - 如何正确转换 n 皇后数组输出

C 指针和链表