In chess, the rook is a piece that can move any number of squares vertically or horizontally. In this problem we will consider small chess boards (at most 44) that can also contain walls through which rooks cannot move. The goal is to place as many rooks on a board as possible so that no two can capture each other. A configuration of rooks is legal provided that no two rooks are on the same horizontal row or vertical column unless there is at least one wall separating them.
The following image shows five pictures of the same board. The first picture is the empty board, the second and third pictures show legal configurations, and the fourth and fifth pictures show illegal configurations. For this board, the maximum number of rooks in a legal configuration is 5; the second picture shows one way to do it, but there are several other ways.
Your task is to write a program that, given a description of a board, calculates the maximum number of rooks that can be placed on the board in a legal configuration.
4 .X.. .... XX.. .... 2 XX .X 3 .X. X.X .X. 3 ... .XX .XX 4 .... .... .... .... 0
5 1 5 2 4
八皇后问题,只不过多了几个隔点。暴力回溯即可。
#include <stdio.h> #include <iostream> #include <algorithm> #include <string.h> #include <string> #include <math.h> using namespace std; int a[5][5], n, w; int check(int x, int y) { int i = x - 1, j = x + 1; while (a[i][y] == 0 && i > 0) i--; while (a[j][y] == 0 && j <= n)j++; if (a[i][y] == 1 || a[j][y] == 1) return 0; i = y - 1, j = y + 1; while (a[x][i] == 0 && i > 0) i--; while (a[x][j] == 0 && j <= n)j++; if (a[x][i] == 1 || a[x][j] == 1) return 0; return 1; } void work(int x,int y) { w = max(w, x); for (int i = y; i <= n*n; i++) { int u = (i - 1) / n + 1; int v = (i - 1) % n + 1; if (a[u][v] == 0 && check(u, v)) { a[u][v] = 1; work(x + 1, y + 1); a[u][v] = 0; } } } int main() { while (cin >> n, n) { for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) { char t; cin >> t; if (t == '.') a[i][j] = 0; else a[i][j] = -1; } w = 0; work(0, 1); cout << w << endl; } return 0; }