/* * @lc app=leetcode id=51 lang=java * * [51] N-Queens */ // @lc code=start import java.util.ArrayList; class Solution { public List> solveNQueens(int n) { int[][] m = createMap(n); List> r = new ArrayList<>(); dfsNQueen(r, m, 0, n, 0); return r; } private void dfsNQueen(List> r, int[][] m, int i, int n, int p) { if(i == n && pass(m, n, i)) { r.add(buildRetStr(m)); return; } else if (i>=n) { return; } if(!pass(m,n, i)) { return; } for(int j = p; j{ return new Point(pos.x, pos.y+1); })) { return false; } if(i < s && !checkRowNotEmpty(m, n, i)) { return false; } } return true; } private boolean checkRowNotEmpty(int[][] m, int n, int s) { for(int i=0; i{ return new Point(pos.x+1, pos.y); })) { return false; } } return true; } private boolean checkLeftSlash(int[][] m, int n) { for(int i = 0; i{ return new Point(pos.x+1, pos.y+1); })) { return false; } if(!checkWithStrategy(m, new Point(0, i), n, pos->{ return new Point(pos.x+1, pos.y+1); })) { return false; } } return true; } private boolean checkRightSlash(int[][] m, int n) { for(int i = 0; i{ return new Point(pos.x+1, pos.y-1); })) { return false; } if(!checkWithStrategy(m, new Point(i, n-1), n, pos->{ return new Point(pos.x+1, pos.y-1); })) { return false; } } return true; } private boolean checkWithStrategy(int[][] m, Point pos, int n,Function incrStrategy) { int c = 0; if(m[pos.x][pos.y] !=0) { c++; } for(int i=0;i=n || pos.y>= n || pos.x <0 || pos.y <0) { break; } if(m[pos.x][pos.y] != 0) { c++; if(c>1) { return false; } } } return true; } private int[][] createMap(int n) { int[][] r = new int[n][n]; zset(r); return r; } private void zset(int[][] m) { if(m == null) { return; } for (int i = 0; i < m.length; i++) { if(m[i]==null) { continue; } for(int j = 0; j < m[i].length; j++) { m[i][j] = 0; } } } private List buildRetStr(int[][] m) { List r = new ArrayList(); if(m == null) { return r; } for(int i = 0; i