zoukankan      html  css  js  c++  java
  • 递归八皇后/N皇后问题

    八皇后问题是一个古老而著名的问题,是回溯算法的典型例题。该问题是十九世纪著名的数学家高斯1850年提出:在8X8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。

    using System;
    using System.Collections.Generic;
    using   System.Diagnostics;   


    public class MyClass
    {
        
    static int[] site=new  int[8];  
        
    static    int queenNum=8;
        
    static    int count=0;        //解法数
        public static void Main()
        
    {
            
    //WL();
            Queen(0);
            RL();
        }

        
    public static void Queen(int n)
        
    {
            
    if(queenNum==n)
            
    {
                WL(
    "第{0}种解法",++count);
                
                
    for(int i=0;i<queenNum;i++)
                
    {
                    WL(
    "{0},",site[i]);
                }

                WL(
    "------------------------------------");
                
    return;
            }

            
    else
            
    {
                
    for(int i=0;i<queenNum;i++)
                
    {
                    site[n]
    =i;
                    
    if(IsOk(n))
                        Queen(n
    +1);
                }

            }

        }

        
    public static bool IsOk(int n)
        
    {
            
    for(int i=0;i<n;i++)
            
    {
                
    if(site[i]==site[n])
                    
    return false;
                
    if(Math.Abs(site[i]-site[n])==n-i)
                    
    return false;
            }

            
    return true;
        }

        
    Helper methods
     


    }
  • 相关阅读:
    PHP数组(数组正则表达式、数组、预定义数组)
    面向对象。OOP三大特征:封装,继承,多态。 这个讲的是【封存】
    uvalive 3938 "Ray, Pass me the dishes!" 线段树 区间合并
    LA4329 Ping pong 树状数组
    HDU 1257 最少拦截系统
    HDU 1260 Tickets
    codeforce 621D
    codeforce 621C Wet Shark and Flowers
    codeforce 621B Wet Shark and Bishops
    codeforce 621A Wet Shark and Odd and Even
  • 原文地址:https://www.cnblogs.com/solo/p/1062858.html
Copyright © 2011-2022 走看看