UVA 639 Don't Get Rooked
2012-10-11 13:16
309 查看
简单回溯
CODE:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
const int SIZE = 6;
int MAX;
int maze[SIZE][SIZE];
int N;
int check(int r, int c)
{
int i;
for(i = r-1; i >= 0; i--)
{
if(maze[i][c] == 'Y') return 0;
if(maze[i][c] == 'X') break;
}
for(i = c-1; i >= 0; i--)
{
if(maze[r][i] == 'Y') return 0;
if(maze[r][i] == 'X') break;
}
return 1;
}
void dfs(int i, int s)
{
if(i == N*N)
{
MAX = max(MAX, s);
return ;
}
int r = i/N, c = i%N; //行,列。
if(maze[r][c] == '.' && check(r, c))
{
maze[r][c] = 'Y';
dfs(i+1, s+1);
maze[r][c] = '.';
}
dfs(i+1, s);
}
int main()
{
int i, j;
while(~scanf("%d", &N), N)
{
getchar();
memset(maze, 0, sizeof(maze));
for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
{
scanf("%c", &maze[i][j]);
}
getchar();
}
MAX = -1;
dfs(0, 0);
printf("%d\n", MAX);
}
return 0;
}
CODE:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
const int SIZE = 6;
int MAX;
int maze[SIZE][SIZE];
int N;
int check(int r, int c)
{
int i;
for(i = r-1; i >= 0; i--)
{
if(maze[i][c] == 'Y') return 0;
if(maze[i][c] == 'X') break;
}
for(i = c-1; i >= 0; i--)
{
if(maze[r][i] == 'Y') return 0;
if(maze[r][i] == 'X') break;
}
return 1;
}
void dfs(int i, int s)
{
if(i == N*N)
{
MAX = max(MAX, s);
return ;
}
int r = i/N, c = i%N; //行,列。
if(maze[r][c] == '.' && check(r, c))
{
maze[r][c] = 'Y';
dfs(i+1, s+1);
maze[r][c] = '.';
}
dfs(i+1, s);
}
int main()
{
int i, j;
while(~scanf("%d", &N), N)
{
getchar();
memset(maze, 0, sizeof(maze));
for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
{
scanf("%c", &maze[i][j]);
}
getchar();
}
MAX = -1;
dfs(0, 0);
printf("%d\n", MAX);
}
return 0;
}
相关文章推荐
- uva 639
- UVA639
- uva639(放车问题)-回溯法
- UVA 639 Don't Get Rooked
- UVA 639 (13.08.25)
- UVA 639 - Don't Get Rooked 暴力回溯
- uva 639 Don't Get Rooked (暴力回溯 )
- UVA - 639 Don't Get Rooked
- uva 639 - Don't Get Rooked
- UVa 639 - Don't Get Rooked
- UVa 639 & HOJ 1086 & POJ 1315 - Don't Get Rooked
- uva 639 Don't Get Rooked
- uva639
- UVA 639 - Don't Get Rooked
- UVA 639 - Don't Get Rooked
- uva 639 - Don't Get Rooked
- UVa 639 - Don't Get Rooked 类皇后问题 递归回溯
- UVa 639 - Don't Get Rooked
- POJ1315 UVA639 UVALive5325 Don't Get Rooked
- UVA - 639 Don't Get Rooked