AcWing:1432。チェス盤チャレンジ
この条件を最初に置く
- 各対角線上に最大で1つのピースが存在できます
間違っていたのですが、マトリックス全体の主対角線と副対角線を制限するだけだと思いました。配置できるのは最大で1つだけです。
実際、これは現在の位置に配置された各チェスピースに対応するメイン対角線とサブ対角線です。
エイトクイーンの変形、dfsの列挙で十分
現在の位置(行、列)
サブ対角線に対応するすべての位置:i + j ==行+列
主対角線上の対応する位置:他の人のコードをn +(row-j)として見てください//私は多くのことを学びました
ACコード
import java.util.*;
import static java.lang.System.out;
public class Main{
static int ans = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[][] map = new int[n][n];
// cols 记录当前列是否被访问过、 dia 记录当前副对角线是否被访问过
boolean[] cols = new boolean[n], dia = new boolean[2 * n];
dfs(map, 0, cols, dia, "");
out.println(ans);
}
public static void dfs(int[][] map, int row, boolean[] cols, boolean[] dia, String s){
if(row >= map.length) {
//out.println(s);
ans++;
if(ans <= 3) out.println(s);
return ;
}
int len = map[0].length;
for(int j = 0; j < len; j++) {
// 当前列 没有棋子 && 副对角线 没有棋子 && 当前主对角线没有棋子
if(!cols[j] && !dia[row + j] && map[row][j] == 0) {
// 对角线的
getset(map, row, j, 1);
cols[j] = true; dia[row + j] = true;
dfs(map, row + 1, cols, dia, s + (j + 1) + " ");
// 回溯
getset(map, row, j, -1);
cols[j] = false; dia[row + j] = false;
}
}
}
// 对角线
public static void getset(int[][] map, int row, int col, int val){
//主对角线
int mn = Math.min(row, col), rlen = map.length, clen = map[0].length;
int r = row - mn, c = col - mn;
while(r < rlen && c < clen) {
map[r++][c++] += val;
}
// 副对角线
//for(int i = 0; i < rlen; i++) {
// for(int j = 0; j < clen; j++) {
// if(i + j == row + col) map[i][j] += val;
// }
//}
}
}
主対角部分を最適化する
簡略化する
ACコード
import java.util.*;
import static java.lang.System.out;
public class Main{
static int ans = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[][] map = new int[n][n];
// cols 记录当前列是否被访问过、 dia 记录当前副对角线是否被访问过、master 记录当前主对角线是否被访问过
boolean[] cols = new boolean[n], dia = new boolean[2 * n], master = new boolean[2 * n];
dfs(map, 0, cols, dia, master, "");
out.println(ans);
}
public static void dfs(int[][] map, int row,
boolean[] cols, boolean[] dia, boolean[] master, String s){
if(row >= map.length) {
//out.println(s);
ans++;
if(ans <= 3) out.println(s);
return ;
}
int len = map[0].length;
for(int j = 0; j < len; j++) {
// 当前列 没有棋子 && 副对角线 没有棋子 && 当前主对角线没有棋子
if(!cols[j] && !dia[row + j] && !master[map.length + (row - j)]) {
// 对角线的
cols[j] = true; dia[row + j] = true; master[map.length + (row - j)] = true;
dfs(map, row + 1, cols, dia, master, s + (j + 1) + " ");
// 回溯
cols[j] = false; dia[row + j] = false; master[map.length + (row - j)] = false;
}
}
}
/**
* @Discard 废弃
*/
// 对角线
//public static void getset(int[][] map, int row, int col, int val){
// //主对角线
// int mn = Math.min(row, col), rlen = map.length, clen = map[0].length;
// int r = row - mn, c = col - mn;
// while(r < rlen && c < clen) {
// map[r++][c++] += val;
// }
//}
}