Poj 1321 棋盘问题
Poj 1321 题目链接
一道简单的DFS回溯题目,#代表的是可以放棋子的棋盘,.代表不能放棋子,
//Powered by CK
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N = 10;
int maze[N][N], n, k, ans;
bool judge(int x, int y) {//判断这一步是否可行
for(int i = 0; i < n; i++)
if(maze[x][i] == 2 || maze[i][y] == 2) return false;
return true;
}
void dfs(int pos, int sum) {
if(sum == k) {
ans ++;
return ;
}
if(pos == n * n) return;//这里就是简化了判断x, y轴的越界问题。
int x = pos / n, y = pos % n;
if(!maze[x][y] && judge(x, y)) {
maze[x][y] = 2;//标记,还要记得回溯
dfs(pos + 1, sum + 1);
maze[x][y] = 0;
}
dfs(pos + 1, sum);
}
int main() {
while(scanf("%d %d", &n, &k) && n != -1) {
for(int i = 0; i < n; i++) {
getchar();
for(int j = 0; j < n; j++) {
char c;
scanf("%c", &c);
if(c == '#') maze[i][j] = 0;//预先处理0代表棋盘可走部分,1代表不可走
else maze[i][j] = 1;
}
}
ans = 0;
dfs(0, 0);
printf("%d\n", ans);
}
return 0;
}