zoukankan      html  css  js  c++  java
  • 递归回溯--八皇后

      

    #include <stdio.h>
    
    #define N 8
    
    int matrix[N][N];    //棋盘矩阵
    int cnt;
    
    int Jude(int row, int col)
    {
        int i,j;
        for (i = 0; i < row; i++)
        {
            for (j = 0; j < N; j++)
            {
                if (matrix[i][j] == 1)
                    if( j == col || i + j == row + col
                    || i - j == row - col || j - i == col -row
                    || i + j == row + col)
                {
                    return -1;
                }
            }
        }
        return 0;
    }
    
    void Print()
    {
        int row, col;
        for (row = 0; row < N; row ++)
        {
            for (col = 0; col < N; col++)
            {
                printf("%d ",matrix[row][col]);
            }
            printf("
    ");
        }
        printf("
    ");
    }
    
    int Queen(int row)
    {
        int col, ret;
    
        if (N == row)
        {
            Print();
            cnt ++;
            return 0;
        }
    
        for (col = 0; col < N; col++)
        {
            ret = Jude(row,col);
            if (0 == ret)
            {
                matrix[row][col] = 1;
                Queen(row + 1);
                matrix[row][col] = 0;
            }
        }
    
        if (col == N) return -1;    //无位置可填
    
        return 0;
    }
    
    int main()
    {
        cnt = 0;
    
        Queen(0);
        printf("Total: %d
    ",cnt);
    
        return 0;
    }
    
    2013/11/10  10:40  cost:40
  • 相关阅读:
    select函数
    ascy_finder|base|cookie 代码测试
    正则表达式之道
    教务系统破解
    jquery API
    test
    如何获取和发送Http请求和相应
    header中ContentDisposition的作用
    Performance Testing 系列
    LINQ
  • 原文地址:https://www.cnblogs.com/Jason-Damon/p/3416424.html
Copyright © 2011-2022 走看看