zoukankan      html  css  js  c++  java
  • 写了一个八皇后解法

    先用最笨的穷举法求解,有空再研究更好的解法:

    # -*- coding: gb2312 -*-

    size 
    = 8      # 棋盘大小
    EMPTY = "O"   # 空位
    QUEEN = "X"   # 皇后

    # 查看棋盘的信息
    def show_board(cols):
        
    for i in range(1, size + 1):
            
    for j in range(1, size + 1):
                
    if j == cols[i]:
                    
    print QUEEN,
                
    else:
                    
    print EMPTY,
            
    print "\n",

    # 检测棋盘上皇后摆法是否合法
    #
     return:
    #
            True(不冲突), False(有冲突)
    def check_board(cols):
        
    for i in range(1, size):
            
    for j in range(i + 1, size + 1):
                
    if (j - i) == abs(cols[j] - cols[i]):
                    
    return False
        
    return True

    solve_count 
    = 0

    for a in range(1, size + 1):
        
    for b in range(1, size + 1):
            
    for c in range(1, size + 1):
                
    for d in range(1, size + 1):
                    
    for e in range(1, size + 1):
                        
    for f in range(1, size + 1):
                            
    for g in range(1, size + 1):
                                
    for h in range(1, size + 1):
                                    
    if a <> b and a <> c and a <> d and a <> e and a <> f and a <> g and a <> h and b <> c and b <> d and b <> e and b <> f and b <> g and b <> h and c <> d and c <> e and c <> f and c <> g and c <> h and d <> e and d <> f and d <> g and d <> h and e <> f and e <> g and e <> h and f <> g and f <> h and g <> h:
                                        cols 
    = [0,a,b,c,d,e,f,g,h]
                                        
    if check_board(cols):
                                            solve_count 
    += 1
                                            show_board(cols)
                                            
    print "\n",

    print "found %i solves." % solve_count

  • 相关阅读:
    mac Redis相关配置,安装,启动,环境的配置。
    MySQL设置global变量和session变量的两种方法详解
    关于MySQL的锁以及数据脏读,重复读,幻读的笔记。
    MySQL新增数据,存在就更新,不存在就添加(转帖加实测)
    selenium 的显示等待和隐式等待的区别(记录加强版)
    MySQL字段与表的注释。转帖
    mysql格式化日期(转帖)
    通过Python用pymysql,通过sshtunnel模块ssh连接远程数据库。
    java io流
    openID 无效
  • 原文地址:https://www.cnblogs.com/RChen/p/313287.html
Copyright © 2011-2022 走看看