国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

Leetcode 51. N-Queens

2019-11-08 02:32:34
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

Leetcode

51. 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..”] ] 原題可以查看 https://leetcode.com/problems/n-queens/?tab=Description

解題思路: 深度優(yōu)先搜索,進(jìn)行遍歷,若當(dāng)前位置可以放“皇后”,則對(duì)下一行的位置進(jìn)行遍歷。下面給出代碼:

public class Solution { public List<List<String>> solveNQueens(int n) { List<List<String>> result = new ArrayList<>(); int[] recorder = new int[n+1]; dfs(1,n,recorder,result); return result; }//通過(guò)recorder 的記錄給出其中一個(gè)可能的棋盤(pán)擺放結(jié)果 private List<String> generateBlock(int []recorder,int n){ List<String> block = new ArrayList<String>(); for(int i=1;i<=n;i++){ StringBuilder strBuilder = new StringBuilder(); for(int j=1;j<=n;j++){ if(recorder[i]==j){ strBuilder.append("Q"); }else{ strBuilder.append("."); } } block.add(strBuilder.toString()); } return block; }//檢查第x行,第y列能否放“皇后” private boolean put(int x,int y,int[]recorder){ for(int i=1;i<x;i++){ int dx = Math.abs(x-i); int dy = Math.abs(y-recorder[i]); if(dx==dy||dy==0) return false; } return true; }//深度搜索 private void dfs(int row,int n,int[]recorder,List<List<String>> result){ if(row>n){ result.add(generateBlock(recorder,n)); return; } for(int i=1;i<=n;i++){ if(put(row,i,recorder)){ recorder[row]=i; dfs(row+1,n,recorder,result); } } }}

這里寫(xiě)圖片描述

歡迎大家提出寶貴意見(jiàn)。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 始兴县| 湖南省| 夏邑县| 通城县| 班玛县| 尉氏县| 无极县| 广河县| 米易县| 仙游县| 湟源县| 南靖县| 汉川市| 和田市| 辽阳市| 仲巴县| 葫芦岛市| 玛沁县| 大名县| 莱芜市| 新邵县| 乌鲁木齐县| 密云县| 北安市| 大石桥市| 河北区| 仁怀市| 平舆县| 敖汉旗| 资源县| 武平县| 沙坪坝区| 于都县| 扎囊县| 闽侯县| 香格里拉县| 山东省| 侯马市| 固原市| 云安县| 平湖市|