[LeetCode]N-Queens I and II
2015-03-13 16:43
288 查看
两个题是一个意思,只不过第一题需要记录所有的解的类型。
第一题的代码:
def isValid(n, colValue):
for x in xrange(0,n):
if colValue
== colValue[x] or abs(colValue
-colValue[x]) == n - x :
return False
return True
def findSol(nQueens, result, row, colValue):
# print row, colValue
if row == nQueens:
sol = []
for x in xrange(0,nQueens):
temp = ""
for y in xrange(0,nQueens):
if y == colValue[x]:
temp+= "Q"
else:
temp += "."
sol.append(temp)
result.append(sol)
else:
for x in xrange(0,nQueens):
colValue[row] = x
if isValid(row, colValue):
findSol(nQueens, result, row+1, colValue )
class Solution:
# @return a list of lists of string
def solveNQueens(self, n):
cValue = []
for x in xrange(0,n):
cValue.append(0)
result = []
findSol(n, result, 0, cValue )
return result
sol = Solution()
sol.solveNQueens(4)
关键的点:
1. 用colValue
来记录第n行的皇后放在第几列。因为一行肯定只有一个皇后,所以根本不用考虑有皇后在同一行的情况。也就是说colValue[i]表示第i行的皇后放在第colValue[i]列;
2. isValid函数。通过输入行号n,判断第n行的列值是否合法。也就是说与其他行的皇后有没有在同列或者同一斜线上;
3.对每一行的皇后,遍历所有的列值,得到合理的解就继续求下一行的皇后,直到所有的皇后位置都确定下来。
第一题的代码:
def isValid(n, colValue):
for x in xrange(0,n):
if colValue
== colValue[x] or abs(colValue
-colValue[x]) == n - x :
return False
return True
def findSol(nQueens, result, row, colValue):
# print row, colValue
if row == nQueens:
sol = []
for x in xrange(0,nQueens):
temp = ""
for y in xrange(0,nQueens):
if y == colValue[x]:
temp+= "Q"
else:
temp += "."
sol.append(temp)
result.append(sol)
else:
for x in xrange(0,nQueens):
colValue[row] = x
if isValid(row, colValue):
findSol(nQueens, result, row+1, colValue )
class Solution:
# @return a list of lists of string
def solveNQueens(self, n):
cValue = []
for x in xrange(0,n):
cValue.append(0)
result = []
findSol(n, result, 0, cValue )
return result
sol = Solution()
sol.solveNQueens(4)
关键的点:
1. 用colValue
来记录第n行的皇后放在第几列。因为一行肯定只有一个皇后,所以根本不用考虑有皇后在同一行的情况。也就是说colValue[i]表示第i行的皇后放在第colValue[i]列;
2. isValid函数。通过输入行号n,判断第n行的列值是否合法。也就是说与其他行的皇后有没有在同列或者同一斜线上;
3.对每一行的皇后,遍历所有的列值,得到合理的解就继续求下一行的皇后,直到所有的皇后位置都确定下来。
相关文章推荐
- LeetCode题解:N-Queens I and II
- Leetcode: Best Time to Buy and Sell Stock II
- LeetCode : Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock I II III
- leetcode Best Time to Buy and Sell Stock I&&II&&III
- [LeetCode]Best Time to Buy and Sell Stock II
- [LeetCode]Best Time to Buy and Sell Stock II
- [leetcode]Best Time to Buy and Sell Stock II
- 【leetcode】Best Time to Buy and Sell Stock II
- LeetCode_Best Time to Buy and Sell Stock II
- [Leetcode]Best Time to Buy and Sell Stock II
- [leetcode]Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- LeetCode - Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- 【LeetCode with Python】 Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock II
- [leetcode]Best Time to Buy and Sell Stock II