简单搜索题。关键是搜索状态的确定以及判断是否重复的方法。记得回溯,可能存在多种解但不一定是最大的。

1、状态从左至右,从上至下去搜索的。

2、由于是从上之下,从左至右搜索的,所以是要判断是否重复就看头顶上是否存在炮点,左手边是否存在炮点就行了。

CODE:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
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 >?= 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, 0sizeof(maze));
        for(i = 0; i < N; i++)
        {
            for(j = 0; j < N; j++)
            {
                scanf("%c", &maze[i][j]);
            }
            getchar();
        }
        MAX = -1;
        dfs(00);
        printf("%d\n", MAX);
    }
    return 0;

} 

posted on 2012-08-18 21:23  有间博客  阅读(177)  评论(0编辑  收藏  举报