题解 | #N皇后问题#
N皇后问题
https://www.nowcoder.com/practice/c76408782512486d91eea181107293b6
总结:
1.解决n皇后问题需要使用dfs解决,由于棋子不能同行同列,同一条斜线,需要先判断是否满足这一条件。左斜线的满足行列序号和相同,右斜线的点满足行列值序号差相同。为了保证查询条件时间复杂度为O1,故将该条件值保存在HashSet,使得查询速度为O1。
import java.util.*; public class Solution { /** * * @param n int整型 the n * @return int整型 */ private List<int[]> result = new ArrayList<>(); int num = 0; public int Nqueen (int n) { // write code here int[] path = new int[n]; Set<Integer> column = new HashSet<>(); Set<Integer> dignoal1 = new HashSet<>(); Set<Integer> dignoal2 = new HashSet<>(); Arrays.fill(path,-1); dfs(path,n,0,column,dignoal1,dignoal2); return num; } public void dfs(int[] path,int n,int row,Set<Integer> column,Set<Integer> dignoal1,Set<Integer> dignoal2){ if(row==n){ result.add(path); num++; return; } for(int i=0;i<n;i++){ if(column.contains(i)) continue; int left = row+i; if(dignoal1.contains(left)) continue; int right = row-i; if(dignoal2.contains(right)) continue; path[row]=i; column.add(i); dignoal1.add(left); dignoal2.add(right); dfs(path,n,row+1,column,dignoal1,dignoal2); path[row] = -1; column.remove(i); dignoal1.remove(left); dignoal2.remove(right); } } }