状态压缩动态规划 -- 棋盘问题 POJ 1321

时间:2014-06-22 06:49:10   收藏:0   阅读:239


一个 N * N 的棋盘上面,有些格子不能放,放置 M 的棋子,

每两个棋子不能在同一行或者同一列,问有多少种放法

DFS太慢,用SCR好点点

Python 只有 22 行,其实可以更短,但是得排成很长很长的一行


while True:
    table = [ [ 0 for j in range( 300 ) ] for i in range( 12 ) ]
    table[0][0] = 1
    boardsize, chessnum = map( int, raw_input().split() ) 
    if boardsize == chessnum == -1: break
    states = range( 1 << boardsize )
    cols = raws = range( 1, boardsize + 1 )
    chessboard = dict( zip( raws, [ ' ' + raw_input() for i in raws ] ) )
    ones = dict( zip( states, map( lambda s: str( bin( s ) ).count( '1' ), states ) ) )
    
    for raw in raws:
        for state in states:
            if ones[state] <= chessnum:
                table[raw][state] += table[raw - 1][state]
                for col in cols:
                    s = 1 << ( col - 1 )
                    if chessboard[raw][col] == '#' and state & s == 0:
                        nextstate = state | s
                        table[raw][nextstate] += table[raw - 1][state]
                        
    print sum( [ table[boardsize][state] for state in states if ones[state] == chessnum ] )


状态压缩动态规划 -- 棋盘问题 POJ 1321,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!