UVA - 639 Don't Get Rooked (回溯)

来源:互联网 发布:linux虚拟机和双系统 编辑:程序博客网 时间:2024/05/18 02:32

 Don't Get Rooked 

In chess, the rook is a piece that can move any number of squaresvertically or horizontally. In this problem we will consider smallchess boards (at most 4$\times$4) that can also contain walls through whichrooks cannot move. The goal is to place as many rooks on a board aspossible so that no two can capture each other. A configuration ofrooks islegal provided that no two rooks are on the samehorizontal row or vertical column unless there is at least one wallseparating them.


The following image shows five pictures of the same board. Thefirst picture is the empty board, the second and third pictures show legalconfigurations, and the fourth and fifth pictures show illegal configurations.For this board, the maximum number of rooks in a legal configurationis 5; the second picture shows one way to do it, but there are severalother 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 theboard in a legal configuration.

Input 

The input file contains one or more board descriptions, followed bya line containing the number 0 that signals the end of the file. Eachboard description begins with a line containing a positive integernthat is the size of the board; n will be at most 4. The nextnlines each describe one row of the board, with a `.' indicating anopen space and an uppercase `X' indicating a wall. There are nospaces in the input file.

Output 

For each test case, output one line containing themaximum number of rooks that can be placed on the boardin a legal configuration.

Sample Input 

4.X......XX......2XX.X3.X.X.X.X.3....XX.XX4................0

Sample Output 

51524


题目大意:
这是一道类似于N皇后的问题,叫我们将车放到小棋盘上面去,规则也类似,让每个车都不能攻击到其他车,
然后有墙阻隔,车是不能攻击到墙后的车的。

解析:用回溯法来解决这个问题。
定义一个vis数组,先将棋盘的情况读入,如果该点未被访问过,且不能攻击到4个方向的车,而且该点为'.',
该点访问就将vis[i][j]置为1,然后递归且将sum+1,因为是回溯法最后别忘了把vis[i][j]置为0。

#include <stdio.h>#include <string.h>const int INF = -0x3f3f3f;const int N = 10;int vis[N][N];char grid[N][N];int n;int max;bool judge(int r,int c) {bool flag = true;for(int i = r-1; i >= 0; i--) {if(vis[i][c]) {flag = false;}else if(grid[i][c] == 'X') {break;}}for(int i = r+1; i < n; i++) {if(vis[i][c]) {flag = false;}else if(grid[i][c] == 'X') {break;}}for(int i = c-1; i >=0; i--) {if(vis[r][i]) {flag = false;}else if(grid[r][i] == 'X') {break;}}for(int i = c+1; i < n; i++) {if(vis[r][i]) {flag = false;}else if(grid[r][i] == 'X') {break;}}return flag;}void dfs(int r,int c,int sum) {for(int i = 0; i < n; i++) {for(int j = 0; j < n; j++) {if(grid[i][j] == '.' && judge(i,j)&& !vis[i][j]) {vis[i][j] = true;dfs(i,j,sum+1);vis[i][j] = false;}}}if(max < sum) {max = sum;}}int main() {while(scanf("%d",&n) != EOF && n) {memset(grid,0,sizeof(grid));memset(vis,0,sizeof(vis));for(int i = 0; i < n; i++) {scanf("%s",grid[i]);}max = INF;dfs(0,0,0);printf("%d\n",max);}return 0;}


0 0
原创粉丝点击