AcWing:1432. 棋盘挑战
一开始把这个条件
- 每条对角线上都最多只能有一个棋子
理解错了,以为只是说限定整个矩阵的主对角线 and 副对角线上都只能最多放一个棋子
其实是在当前位置放下的每个棋子对应的主对角线 and 副对角线.
八皇后变形, dfs 枚举即可
当前位置(row, col)
副对角线上对应的所有位置: i + j == row + col
主对角线上对应的所有位置: 看别人的代码是 n + (row - j) // 长见识了
AC Code
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 Code
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;
// }
//}
}