754B Ilya and tic-tac-toe game

本文介绍了一个使用BFS解决CodeForces平台B题的方法。通过定义八个方向的移动,利用队列进行广度优先搜索,并标记已访问位置避免重复搜索。此方法适用于在4x4棋盘上寻找特定条件的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:

http://codeforces.com/problemset/problem/754/B

题解:

感觉这题直接用暴力去做(虽然自己比较傻的用了BFS做)

代码:

#include <cmath>
#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define met(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
typedef long long ll;
int dir[8][2]={1,0,-1,0,0,1,0,-1,1,1,1,-1,-1,1,-1,-1};
struct node
{
    int x,y;
};
int visited[4][4];
char map[4][4];
int flag;

bool go(int x,int y)
{
    if(0<=x&&x<4&&0<=y&&y<4&&(map[x][y]=='.'||map[x][y]=='x'))
       return true;
    return false;
}

void bfs(int x,int y)
{
    node  now,next;
    queue<node>q;
    while(!q.empty())
        q.pop();
    met(visited,0);
    now.x=x;
    now.y=y;
    visited[x][y]=1;
    q.push(now);
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        for(int i=0;i<8;i++)
        {
            next.x=now.x+dir[i][0];
            next.y=now.y+dir[i][1];
            int cnt1=1;
            int cnt2=0;
            if(map[now.x][now.y]=='x')
                cnt2=1;
            if(!visited[next.x][next.y]&&go(next.x,next.y))
            {
                visited[next.x][next.y]=1;
                q.push(next);
            }
            while(go(next.x,next.y))
            {
                cnt1++;
                if(map[next.x][next.y]=='x')
                    cnt2++;
                if(cnt1==3&&cnt2>=2)
                {
                    printf("YES\n");
                    flag=1;
                    return;
                }
                next.x+=dir[i][0];
                next.y+=dir[i][1];
            }
        }
    }
}

int main()
{
    for(int i=0;i<4;i++)
        scanf("%s",map[i]);
    flag=0;
    for(int i=0;i<4;i++)
        for(int j=0;j<4;j++)
            if(!flag&&(map[i][j]=='x'||map[i][j]=='.'))
               bfs(i,j);
    if(!flag)
        printf("NO\n");

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值