Leet Code 51 N-Queens - N皇后问题 - Java
2016-06-23 00:00
211 查看
摘要: Leet Code 51 N-Queens - N皇后问题 - Java
问题原始链接 https://leetcode.com/problems/n-queens
N皇后问题,在 N*N 的棋盘上放 N 个皇后,任意两个皇后不相互攻击。
给定整数 n,返回 n皇后的所有不同的解。
解中 'Q' 和 '.' 分别表示皇后和空格子。
例如,4皇后问题有两个不同的解:
[
[".Q..", // 解1
"...Q",
"Q...",
"..Q."],
["..Q.", // 解2
"Q...",
"...Q",
".Q.."]
]
问题原始链接 https://leetcode.com/problems/n-queens
N皇后问题,在 N*N 的棋盘上放 N 个皇后,任意两个皇后不相互攻击。
给定整数 n,返回 n皇后的所有不同的解。
解中 'Q' 和 '.' 分别表示皇后和空格子。
例如,4皇后问题有两个不同的解:
[
[".Q..", // 解1
"...Q",
"Q...",
"..Q."],
["..Q.", // 解2
"Q...",
"...Q",
".Q.."]
]
public class Solution { public List<List<String>> solveNQueens(int n) { List<List<String>> result = new ArrayList<List<String>>(); if (n <= 0) { return result; } place(new int , 0, new StringBuilder(n), result); return result; } private static void place(int[] rowToCol, int row, StringBuilder printer, List<List<String>> result) { if (row == rowToCol.length) { print(rowToCol, printer, result); return; } for (int col = 0; col < rowToCol.length; col++) { rowToCol[row] = col; if (!isAttack(rowToCol, row)) { place(rowToCol, row + 1, printer, result); } } } private static boolean isAttack(int[] rowToCol, int row) { for (int preRow = 0; preRow < row; preRow++) { if (Math.abs(row - preRow) == Math.abs(rowToCol[preRow] - rowToCol[row]) || rowToCol[row] == rowToCol[preRow]) { return true; } } return false; } private static void print(int[] rowToCol, StringBuilder printer, List<List<String>> result) { List<String> solution = new ArrayList<String>(); for (int row = 0; row < rowToCol.length; row++) { solution.add(printRow(rowToCol, row, printer)); } result.add(solution); } private static String printRow(int[] rowToCol, int row, StringBuilder printer) { printer.setLength(0); for (int col = 0; col < rowToCol[row]; col++) { printer.append("."); } printer.append("Q"); for (int col = rowToCol[row] + 1; col < rowToCol.length; col++) { printer.append("."); } return printer.toString(); } }
相关文章推荐
- c++递归实现n皇后问题代码(八皇后问题)
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解