天天看点

[HDU3683 Gomoku]

[关键字]:枚举

[题目大意]:给出一盘五子棋局,判断在3步内是否有人能赢。

//=============================================================================================================================

[分析]:首先考虑第一步就有人赢的情况:枚举全棋盘所有可以放子的点判断在此处放一颗子后当前先手是否能赢;第二步才有人赢的情况:当前后手有两处地方可以保证走一步就能赢,因为如果只有一处,先手可以在此放子,但有两处的话先手顾此失彼;第三步才有人赢的情况:比上两种情况稍微复杂,首先如果当前后手有一种必胜情况,则将此处放上自己的子然后等同与判断新棋局两步是否能赢(上面情况二),如果当前后手没有必胜情况怎枚举全盘可以放子的地方放一颗子,在按情况二处理。很简单,注意细节就没问题。

[代码]:

View Code

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;

const int dx[4]={0,1,1,1};
const int dy[4]={1,1,0,-1};
const char S[][6]={"white","black"};

int N,Sx,Sy;
int map[15][15],sum[2];

void Init()
{
    memset(map,255,sizeof(map));
    memset(sum,0,sizeof(sum));
for (int i=1;i<=N;i++)
    {
int x,y,c;
        scanf("%d%d%d",&x,&y,&c);
        map[x][y]=c;
        sum[c]++;
    }
/*for (int i=0;i<15;i++)
    {
        for (int j=0;j<15;j++) printf(" %d ",map[i][j]);
        printf("\n");
    }*/
}

bool Cleck(int sx,int sy,int o)
{
for (int i=0;i<4;i++)
    {
int xx=sx,yy=sy,s1=0;
for (int j=0;j<4;j++)
        {
            xx=xx+dx[i],yy=yy+dy[i];
if (xx<0 || xx>=15 || yy<0 || yy>=15 || map[xx][yy]!=o) break;
            s1++;
        }
        xx=sx,yy=sy;
for (int j=0;j<4;j++)
        {
            xx=xx-dx[i],yy=yy-dy[i];
if (xx<0 || xx>=15 || yy<0 || yy>=15 || map[xx][yy]!=o) break;
            s1++;
        }
if (s1>=4) return 1;
    }
return 0;
}

void Solve(int o)
{
int tot=0;
for (int i=0;i<15;i++)
for (int j=0;j<15;j++)
if (map[i][j]==-1) 
if (Cleck(i,j,o)) {printf("Place %s at (%d,%d) to win in 1 move.\n",S[o],i,j);return;}
    o=!o,tot=0;
for (int i=0;i<15;i++)
for (int j=0;j<15;j++)
if (map[i][j]==-1)
            {
if (Cleck(i,j,o)) tot++,Sx=i,Sy=j;
if (tot==2) {printf("Lose in 2 moves.\n");return;}
            }
    o=!o;
if (tot==1)
    {
        tot=0;
        map[Sx][Sy]=o;
for (int i=0;i<15;i++)
for (int j=0;j<15;j++)
if (map[i][j]==-1)
                {
if (Cleck(i,j,o)) tot++;
if (tot==2) {printf("Place %s at (%d,%d) to win in 3 moves.\n",S[o],Sx,Sy);return;}
                }
    }
else 
    {
for (int i=0;i<15;i++)
for (int j=0;j<15;j++)
if (map[i][j]==-1)
                {
                    map[i][j]=o;
                    tot=0;
for (int i1=0;i1<15;i1++)
for (int j1=0;j1<15;j1++)
if (map[i1][j1]==-1)
                            {
if (Cleck(i1,j1,o)) tot++;
if (tot==2) {printf("Place %s at (%d,%d) to win in 3 moves.\n",S[o],i,j);return;}
                            }
                    map[i][j]=-1;
                }
    }
    printf("Cannot win in 3 moves.\n");
}

int main()
{
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
while (scanf("%d",&N),N)
    {
        Init();
if (sum[1]==sum[0]) Solve(1);
else if (sum[1]==sum[0]+1) Solve(0);
else printf("Invalid.\n");
    }
return 0;
}      

转载于:https://www.cnblogs.com/procedure2012/archive/2012/03/01/2376027.html