UVa 639 - Don't Get Rooked

Contents

  1. 1. Problem
  2. 2. Solution
  3. 3. Code

Problem

中文網址

Solution

明明不難卻寫好久…
只要可以放就以此盤面繼續遞迴下去,否則往下一格。

Code

UVa 639
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include<cstdio>

int n, count, max;
char board[6][6];
bool rook[6][6];
inline bool isOk(int r, int c)
{
int i;
for (i = r; board[i][c] && board[i][c] != 'X'; i--)
if (rook[i][c])
return false;
for (i = r; board[i][c] && board[i][c] != 'X'; i++)
if (rook[i][c])
return false;
for (i = c; board[r][i] && board[r][i] != 'X'; i--)
if (rook[r][i])
return false;
for (i = c; board[r][i] && board[r][i] != 'X'; i++)
if (rook[r][i])
return false;

return true;
}
void dfs(int r);
int main()
{
while (scanf("%d", &n) && n)
{
getchar();
int i, j;
for (i = 0; i <= n + 1; i++)
board[i][0] = board[0][i] = NULL;

for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
board[i][j] = getchar();
getchar();
}

for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
rook[i][j] = false;

count = max = 0;
dfs(1);
printf("%d\n", max);
}

return 0;
}
void dfs(int r)
{
for (; r <= n; r++)
{
for (int j = 1; j <= n; j++)
{
if (board[r][j] != 'X'&&isOk(r, j))//可以放才繼續做下去
{
rook[r][j] = true;
count++;

dfs(r);

rook[r][j] = false;
count--;
}
}
}

if (r > n)
max = max > count ? max : count;
}