[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. ...
随机推荐
- bzoj1630 [Usaco2007 Demo]Ant Counting
Description Bessie was poking around the ant hill one day watching the ants march to and fro while g ...
- C++静态成员函数不能调用非静态成员变量
其实我们从直观上可以很好的理解静态成员函数不能调用非静态成员变量这句话因为无论是静态成员函数还是静态成员变量,它们 都是在类的范畴之类的,及在类的整个生存周期里始终只能存在一份.然而非静态成员变量和非 ...
- Java语言程序设计(基础篇) 第八章 多维数组
第八章 多维数组 8.2 二维数组的基础知识 二维数组中的元素通过行和列的下标来访问. 8.2.1 声明二维数组变量并创建二维数组 下面是二维数组的语法: 数据类型[][] 数组名; int[][] ...
- eclipse中误删了servers文件
Eclipse中误删了servers文件,需要重新添加tomcat服务器,这时就会遇到在New Server对话框中选择了Tomcat 6/7后却无法单击"Next"按钮的问题,如 ...
- 谱聚类--SpectralClustering
谱聚类通常会先对两两样本间求相似度. 然后依据相似度矩阵求出拉普拉斯矩阵,然后将每一个样本映射到拉普拉斯矩阵特诊向量中,最后使用k-means聚类. scikit-learn开源包中已经有现成的接口能 ...
- 4. Linux 系统目录
一.Linux 系统目录的作用 /home 用户主目录的根节点,所有用户自己独有的文件一般放在这个目录下的用户目录下 /bin 二进制可执行命令 / ...
- nodejs实现接收Snmp的Trap消息
var assert = require('assert'); var ASN1 = { EOC: 0, Boolean: 1, Integer: 2, BitString: 3, OctetStri ...
- js 倒计时 已过去时间
页面中的代码: <strong id="timer" datatime="2012-12-09 10:20:30"></strong> ...
- wpf中,一个简单的自定义treeview
首先创建一个自定义控件,在里面定义好treeview的样式,将本来的三角形的图标变为加号的图标,并且添加节点之间的连线. <UserControl x:Class="TreeViewE ...
- JSP合用html5 尝试(一)
直接上代码 <%@page pageEncoding="utf-8" contentType="text/html;charset=utf-8" %> ...