国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 揭阳市| 民权县| 板桥市| 海安县| 清水河县| 叙永县| 丰镇市| 石城县| 萨嘎县| 乳山市| 万山特区| 游戏| 大兴区| 家居| 张掖市| 明水县| 海南省| 寻甸| 庆云县| 天台县| 辽宁省| 苏尼特右旗| 海原县| 民县| 酒泉市| 宁阳县| 屯昌县| 威海市| 永清县| 垣曲县| 正定县| 柞水县| 南召县| 孟州市| 临沧市| 辉南县| 鹰潭市| 抚顺市| 鹰潭市| 视频| 定安县|