zoukankan      html  css  js  c++  java
  • 八皇后问题

     经典的八皇后问题。。

    #define LEN 8
    
    int count = 0;
    
    void eightQueen(int chess[][8], int row);
    int isSafe(int chess[][8], int row, int col);
    
    int main(int argc, char *argv[])
    {
        int chess[LEN][LEN];
        int i, j;
        
        for(i = 0; i<LEN; i++)
        {
            for(j = 0; j < LEN; j++)
            {
                chess[i][j] = 0;
            }
        }
        
        eightQueen(chess, 0);
        printf("共有%d种方案", count);
        return 0;
    }
    
    void eightQueen(int (*chess)[8], const int row)
    {
        int chess2[LEN][LEN];
        int i,j, k; 
        for(i = 0; i< LEN; i++)
        {
            for(j = 0; j< LEN; j++)
            {
                //printf("%d ", *(*((chess)+i)+j) );
                chess2[i][j] = *(*(chess+i)+j);
            }
        }
    
        if(row==LEN)
        {
            count += 1;
            printf("第 %d 种方案
    ", count);
            for(i = 0; i< LEN; i++)
            {
                for(j = 0; j< LEN; j++)
                {
                    printf("%d ", chess2[i][j]);
                }
                printf("
    ");
            }
            printf("
    ");
            
        }else {
            
            for(j = 0; j<LEN; j++)
            {
                for(k = 0; k<j; k++)
                {
                    chess2[row][k] = 0;
                }
                
                if(!isSafe(chess2, row, j))
                {
                    chess2[row][j] = 1;
                    eightQueen(chess2, row+1);
                }
            }
        }
    }
    
    int isSafe(int (*chess)[8], const int row, const int col)
    {
        int i,j,res = 0;
        
        for(i = row; i>=0; i--)
        {
            if(*(*(chess+i)+col) == 1)
            {
                res = 1;
                break;
            }
        }
        
        if(res == 1)
        {
            return res;
        }
        
        for(i = row-1, j = col-1; i>=0 && j>=0; i--, j--)
        {
            if(*(*(chess+i)+j) == 1)
            {
                res = 1;
                break;
             } 
        }
        
        if(res == 1)
        {
            return res;
        }
        
        for(i = row-1, j = col+1; i>=0 && j< LEN; i--, j++)
        {
            if(*(*(chess+i)+j) == 1)
            {
                res = 1;
                break;
             }
        } 
        
        if(res == 1)
        {
            return res;
        }
        
        return 0; 
    }

    eightQueen函数中,用k作循环的那一段超级重要,要不然每一行的结果之间就会相互影响。。。。。。

  • 相关阅读:
    apache虚拟主机三种不同配置方式
    搭建http服务器及配置
    学校ftp服务器搭建
    vsftpd搭建使用
    nginx使用
    pxe+kickafkstart (二)转
    pxe批量网络装机
    bash中()使用特性
    ansible使用
    javascript 之 Object.defineProperty
  • 原文地址:https://www.cnblogs.com/buerr/p/7383818.html
Copyright © 2011-2022 走看看