leetcode:N-Queens 【Java】
来源:互联网 发布:比价系统源码 编辑:程序博客网 时间:2024/05/29 18:53
一、问题描述
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.."]]
二、问题分析
1、采用回溯算法;
2、找到一个可行解之后,还需要继续搜索。
三、算法代码
public class Solution { public List<List<String>> solveNQueens(int n) { List<List<String>> result = new ArrayList<>(); if (n <= 0) return result; char[][] board = new char[n][n]; for (char[] row : board) { Arrays.fill(row, '.'); } boolean[] col_occupied = new boolean[n]; placeQueen(result, board, col_occupied, 0, n); return result; } private void placeQueen(List<List<String>> result, char[][] board, boolean[] col_occupied, int rowNum, int n) { if (rowNum == n) { List<String> list = new ArrayList<String>(); for (char[] row : board) { list.add(new String(row)); } result.add(list); return; } for (int colNum=0; colNum<n; colNum++) { if (isValid(board, col_occupied, rowNum, colNum, n)){ board[rowNum][colNum] = 'Q'; col_occupied[colNum] = true; placeQueen(result, board, col_occupied, rowNum+1, n); board[rowNum][colNum] = '.'; //回溯,尝试皇后rowNum的下一个位置 col_occupied[colNum] = false; } } } private boolean isValid(char[][]board, boolean[] col_occupied, int row, int col, int n) { if (col_occupied[col]) return false; for (int i=1; row-i>=0 && col-i>=0; i++) { if (board[row-i][col-i] == 'Q') return false;//反对角斜线 } for (int i=1; row-i>=0 && col+i<n; i++) { if (board[row-i][col+i] == 'Q') return false;//正对角斜线 } return true; }}
0 0
- [Leetcode] N-Queens (Java)
- [LeetCode][Java] N-Queens
- leetcode:N-Queens 【Java】
- N-Queens leetcode java
- [Leetcode] N-Queens II (Java)
- [LeetCode][Java] N-Queens II
- [leetcode-51]N-Queens(java)
- leetcode:N-Queens II 【Java】
- (Java)LeetCode-51. N-Queens
- 【Leetcode】:51. N-Queens 问题 in JAVA
- (Java)LeetCode-52. N-Queens II
- 【LeetCode】N-Queens && N-Queens II
- leetcode N-Queens & N-Queens II
- Leetcode: N-Queens && N-Queens II
- 【Leetcode】【python】N-Queens/N-Queens II
- LeetCode: N-Queens II
- LeetCode: N-Queens
- LeetCode : N-Queens
- 添加path linux
- Install WPF Theme
- C语言中break和continue的区别
- 计算机视觉(ComputerVision, CV)相关领域的网站链接
- Android代码混淆相关
- leetcode:N-Queens 【Java】
- 关于python中,map,reduce,filter,sort函数的用法:
- 点击标签实现特殊样式及阻止hove样式
- Unix的前世今生
- epoll函数的使用
- Android视觉动画效果---未完待续
- C#获取当前日期时间
- SimpleAdapter
- JAVA笔记之equals方法