zoukankan      html  css  js  c++  java
  • 递归的应用实验二

    1.实现八皇后

    #include <stdio.h>

    #define N 8
    //表示 坐标的平移
    typedef struct _tag_Pos
    {
        int ios;
        int jos;
    } Pos;
    //棋盘 --边界不用!
    static char board[N+2][N+2];
    //坐标的初始化
    static Pos pos[] = { {-1, -1}, {-1, 0}, {-1, 1} };
    static int count = 0;
    //初始化棋盘
    void init()
    {
        int i = 0;
        int j = 0;
        //把边界初始化
        for(i=0; i<N+2; i++)
        {
            board[0][i] = '#';
            board[N+1][i] = '#';
            board[i][0] = '#';
            board[i][N+1] = '#';
        }
        //初始化8x8棋盘
        for(i=1; i<=N; i++)
        {
            for(j=1; j<=N; j++)
            {
                board[i][j] = ' ';
            }
        }
    }
    //打印棋盘
    void display()
    {
        int i = 0;
        int j = 1;
        
        for(i=0; i<N+2; i++)
        {
            for(j=0; j<N+2; j++)
            {
                printf("%c", board[i][j]);
            }
            
            printf(" ");
        }
    }
    //对每个方向进行检查
    int check(int i, int j)
    {
        int ret = 1;
        int p = 0;
        
        for(p=0; p<3; p++)
        {
            int ni = i;
            int nj = j;
            
            while( ret && (board[ni][nj] != '#') )
            {
                ni = ni + pos[p].ios;
                nj = nj + pos[p].jos;
                //没皇后--递归
                ret = ret && (board[ni][nj] != '*');
            }
        }
        
        return ret;
    }
    //进行查找边界
    void find(int i)
    {
        int j = 0;
        
        if( i > N )
        {
            count++;
            
            printf("Solution: %d ", count);
            
            display();
            
            getchar();
        }
        else
        {
            for(j=1; j<=N; j++)
            {
                if( check(i, j) )
                {
                    board[i][j] = '*';
                    
                    find(i+1);
                    //清空
                    board[i][j] = ' ';
                }
            }
        }
    }

    int main()
    {
        init();
        find(1);
        
        return 0;
    }

  • 相关阅读:
    Web安全
    前端安全之XSS攻击
    SQL盲注
    Vim使用手册
    VC获取cookies的几种方法
    Wireshark基本介绍和学习TCP三次握手
    细说Cookie
    top100tools
    如何更改Jframe里Jpanel的大小
    HTTP&&Fiddler教程
  • 原文地址:https://www.cnblogs.com/wxb20/p/6142559.html
Copyright © 2011-2022 走看看