[Leetcode][Python]51: N-Queens
# -*- coding: utf8 -*-
'''
__author__ = 'dabay.wang@gmail.com' 51: N-Queens
https://oj.leetcode.com/problems/n-queens/ The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement,
where 'Q' and '.' both indicate a queen and an empty space respectively. For example,
There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."], ["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
===Comments by Dabay===
这套题思路比较简单,先发一个皇后,然后找下一个可能的位置放第二个... 技巧就在“找下一个可能的位置”上,
- 下一个位置,其实就在下一行中
- 检查是否可以放置的时候,只需要检查所在列是否被占用,以及分别向左上和右上是否斜线被占。(因为下面还没有放皇后呐)
'''
class Solution:
# @return a list of lists of string
def solveNQueens(self, n):
def make_solution(board):
copy = []
for row in board:
row_str = ""
for c in row:
row_str = row_str + c
copy.append(row_str)
return copy def check_up(r, c, queen_stack, board):
i = 1
while i < len(board):
if r-i>=0 and c-i>=0 and board[r-i][c-i]=='Q':
return False
if r-i>=0 and c+i<len(board) and board[r-i][c+i]=="Q":
return False
i = i + 1
else:
return True def find_available_positions(board, queen_stack):
positions = []
row = len(queen_stack)
queen_columns = [pos[1] for pos in queen_stack]
for c in xrange(len(board)):
if c in queen_columns:
continue
if board[row][c] == "." and check_up(row, c, queen_stack, board):
positions.append((row,c))
return positions def DFS(board, queen_stack, res):
if len(queen_stack) >= len(board):
res.append(make_solution(board))
return
positions = find_available_positions(board, queen_stack)
for (r, c) in positions:
queen_stack.append((r, c))
board[r][c] = "Q"
DFS(board, queen_stack, res)
queen_stack.pop()
board[r][c] = "." board = [["."] * n for _ in xrange(n)]
queen_stack = []
res = [] DFS(board, queen_stack, res)
return res def print_board(board):
print '-' * 30
for row in board:
for item in row:
print item,
print '-' * 30 def main():
sol = Solution()
solutions = sol.solveNQueens(4)
for solution in solutions:
print_board(solution) if __name__ == "__main__":
import time
start = time.clock()
main()
print "%s sec" % (time.clock() - start)
[Leetcode][Python]51: N-Queens的更多相关文章
- Leetcode Python Solution(continue update)
leetcode python solution 1. two sum (easy) Given an array of integers, return indices of the two num ...
- LeetCode python实现题解(持续更新)
目录 LeetCode Python实现算法简介 0001 两数之和 0002 两数相加 0003 无重复字符的最长子串 0004 寻找两个有序数组的中位数 0005 最长回文子串 0006 Z字型变 ...
- 【LeetCode】51. N-Queens 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 回溯法 日期 题目地址:https://leetco ...
- [Leetcode][Python]52: N-Queens II
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 52: N-Queens IIhttps://oj.leetcode.com/ ...
- [LeetCode][Python]Container With Most Water
# -*- coding: utf8 -*-'''https://oj.leetcode.com/problems/container-with-most-water/ Given n non-neg ...
- 【一天一道LeetCode】#51. N-Queens
一天一道LeetCode系列 (一)题目 The n-queens puzzle is the problem of placing n queens on an n×n chessboard suc ...
- LeetCode Python 位操作 1
Python 位操作: 按位与 &, 按位或 | 体会不到 按位异或 ^ num ^ num = 0 左移 << num << 1 == num * 2**1 右移 & ...
- 【leetcode❤python】Sum Of Two Number
#-*- coding: UTF-8 -*- #既然不能使用加法和减法,那么就用位操作.下面以计算5+4的例子说明如何用位操作实现加法:#1. 用二进制表示两个加数,a=5=0101,b=4=0100 ...
- [Leetcode][Python]56: Merge Intervals
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 56: Merge Intervalshttps://oj.leetcode. ...
随机推荐
- T-SQL 运算符
运算符 1.算术运算符 算术运算符 说明 + 加法 - 减法 * 乘法 / 除法 % 取模,两个整数相除后的余数 2.位运算符 位运算符 说明 &(与.and) 按位逻辑与运算 |(或.OR) ...
- SQL Server索引的维护 - 索引碎片、填充因子 <第三篇>
实际上,索引的维护主要包括以下两个方面: 页拆分 碎片 这两个问题都和页密度有关,虽然两者的表现形式在本质上有所区别,但是故障排除工具是一样的,因为处理是相同的. 对于非常小的表(比64KB小得多), ...
- xargs mv命令使用方法:ls *.mp3 |xargs -i mv {} /tmp
ls *.mp3 |xargs -i mv {} /tmp 或者 find . -name "*.mp3" -exec mv {} /tmp \;
- 【转】Android下编译jni库的二种方法(含示例) -- 不错
原文网址:http://blog.sina.com.cn/s/blog_3e3fcadd01011384.html 总结如下:两种方法是:1)使用Android源码中的Make系统2)使用NDK(从N ...
- C语言中long类型,int类型
long类型表示long int,一般简写为long,注意long不表示long double.虽然有时候会有sizeof(long)=sizeof(int),long int与int是不同的: 16 ...
- Amdroid示例:利用Gson生成或解析json
转自:http://www.cnblogs.com/liqw/p/4266209.html 目前手机端和服务端数据交流格式一般是json,而谷歌提供了Gson来解析json.下载Gson:https: ...
- UESTC_How many good substrings CDOJ 1026
Icerain likes strings very much. Especially the strings only consist of 0 and 1,she call them easy s ...
- ※数据结构※→☆非线性结构(tree)☆============二叉树 顺序存储结构(tree binary sequence)(十九)
二叉树 在计算机科学中,二叉树是每个结点最多有两个子树的有序树.通常子树的根被称作“左子树”(left subtree)和“右子树”(right subtree).二叉树常被用作二叉查找树和二叉堆或是 ...
- OpenRisc-45-or1200的ID模块分析
引言 之前,我们分析了or1200流水线的整体结构,也分析了流水线中IF级,EX级,本小节我们来分析ID(insn decode)级的一些细节. 1,基础 or1200的pipeline的ID阶段包含 ...
- 上传form表单
<form name="theForm" method="post" action="index.php?m=back&c=Goods& ...