[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. ...
随机推荐
- Application.HookMainWindow完全替代了原来的窗口过程(但是好像也会继续传递)
unit HookMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialo ...
- bzoj1644 [Usaco2007 Oct]Obstacle Course 障碍训练课
Description 考虑一个 N x N (1 <= N <= 100)的有1个个方格组成的正方形牧场.有些方格是奶牛们不能踏上的,它们被标记为了'x'.例如下图: . . B x . ...
- web api\ protobuf \formatter
9:50:20吴X2014/11/7 9:50:20 9:55:14吴X2014/11/7 9:55:14webapi实现protobuf吴X2014/11/7 9:56:29http://www.s ...
- Jquery EasyUI修改行背景的两种方式
1.数据加载完成不请求后台的做法 方式一: //更改表格行背景 function changeLineStyle(index){ var rows=$("#alertGird"). ...
- mongoDb c driver
1,yum dependencies Centos,RHEL Fedora: $ sudo yum install git gcc automake autoconf libtool Debian: ...
- 【转】100行代码实现最简单的基于FFMPEG+SDL的视频播放器
FFMPEG工程浩大,可以参考的书籍又不是很多,因此很多刚学习FFMPEG的人常常感觉到无从下手.我刚接触FFMPEG的时候也感觉不知从何学起. 因此我把自己做项目过程中实现的一个非常简单的视频播放器 ...
- 安装MySQLdb-python时无法找到-lprobes_mysql处理一则
安装MySQLdb时,我已经做好了如下两点:1)配置好mysql_config 有两种方式可以做: ① 做个软连接,把mysql_config链接到/usr/local/bin下 ② ...
- mysql(5.7)在CentOs7下的安装、配置与应用
和之前版本的mysql有一些不同,现把完整过程记下来,或许对新手来说有用. 本文描述的安装是采用通用的二进制压缩包(linux - Generic)以解压方式安装,相当于绿色安装了. 一.下载通用 ...
- idea maven 无法加载已经安装的模块
新建了一下maven项目,下面新建了一个模块,某一个模块clean install之后,别的模块虽然使用dependency标签引入了,但是仍然无法使用, 这个时候,应该重新建立一个项目,将原有项目的 ...
- 搭建高可用mongodb集群—— 分片
从节点每个上面的数据都是对数据库全量拷贝,从节点压力会不会过大? 数据压力大到机器支撑不了的时候能否做到自动扩展? 在系统早期,数据量还小的时候不会引起太大的问题,但是随着数据量持续增多,后续迟早会出 ...