[DFS]poj 1321 棋盘问题

来源:互联网 发布:腾讯视频mac 编辑:程序博客网 时间:2024/06/07 01:43

poj 1321 棋盘问题

题意:

规定n*n大小的棋盘,给定棋子数目,求规定棋子数目的摆放方案

思路:

求方案数,dfs更合适吧

1、因为求方案数,注意回溯

2、题目一个坑……,“#”表示才棋盘区域,“.”才相当于墙壁

代码:

#include <iostream>#include <cstdio>#include <algorithm>#include <cmath>#include <cstring>#include <queue>#include <stack>//notice the '#' can be placed.using namespace std;const int MAXN = 10;int n, m;int ans = 0;char my_map[MAXN][MAXN];bool vis_row[MAXN];     //vis_row[i], i row is visited.bool vis_col[MAXN];     //vis_col[j], j col is visited.bool judge(int x, int y){    if(x<0 || x>=n || y<0 || y>=n || my_map[x][y]!='#') return false;    if(vis_row[x] || vis_col[y]) return false;    return true;}void DFS(int x, int y, int step){    //int xx, yy;    if(step == m) {ans++; return;}    for(int i=x; i<n; i++)    for(int j=0; j<n; j++){        if(judge(i, j)){            vis_row[i] = vis_col[j] = true;            DFS(i, j, step+1);            vis_row[i] = vis_col[j] = false;        }    }}int main(){    while(scanf("%d%d", &n, &m) && n!=-1 && m!=-1){        ans = 0;        memset(vis_row, false, sizeof(vis_row));        memset(vis_col, false, sizeof(vis_col));        for(int i=0; i<n; i++) scanf("%s", my_map[i]);        DFS(0, 0, 0);        printf("%d\n", ans);    }    return 0;}/*8 8################################################################---------40320*/


反思:

1、

注意一下,为了避免漏掉和重复,注意DFS()函数的双重循环的初始赋值

    for(int i=x; i<n; i++)    for(int j=0; j<n; j++)
wa的那次写成了

    for(int i=x; i<n; i++)    for(int j=y; j<n; j++)
顺便给个测试数据1,取自 ./poj/discuss/moodyjade

8 8################################################################---------40320

测试数据2,取自 ./poj/discuss/lifeich1

4 2#...##.....#..#.------8
2、

只要一找不到wa的点就去discuss找特殊数据了……完全是一条咸鱼了哭泣

0 0
原创粉丝点击