【CF】D. Arthur and Walls(BFS + 贪心)

博客介绍了如何解决Codeforces竞赛中D题的策略,利用BFS遍历和贪心策略,检查2x2区域内是否有单一'*'并将其转换为'.'。初始将所有'.'加入队列,遇到'*'变为'.'并继续搜索,判断时考虑四个方向。

D题

解题思路就是每次检查2X2的方格里是否只有一个‘*’,如果有的话这个*就需要变成‘.’,利用BFS进行遍历,入队的要求是这个点为.

一开始将所有的'.'全部加入队列,如果碰到一个'*'变成'.'就入队,判断的时候从4个方向就行判断

题目链接:http://codeforces.com/contest/525/problem/D

#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
#include<vector>
#include<cstdlib>
using namespace std;
const int maxn = 2005;
typedef pair<int,int> pill;
const int dir_x[4][3] = {{1,0,1},{0,-1,-1},{-1,-1,0},{1,1,0}};
const int dir_y[4][3] = {{0,1,1},{1,0,1},{0,-1,-1},{0,-1,-1}};
char mat[maxn][maxn];
int  n,m;
void input(){
    for(int i = 0; i < n; i++)
        puts(mat[i]);
}
void bfs(){
    queue<pill>q;
    for(int i = 0; i < n; i++)
        for(int j = 0; j < m; j++)
            if(mat[i][j] == '.') q.push(make_pair(i,j));
    while(!q.empty()){
        pill now = q.front(); q.pop();
        int x = now.first,y = now.second;
        int pos_x,pos_y,cnt;
        for(int i = 0; i < 4; i++){
            cnt = 0;
            int ok = 1;
            for(int j = 0; j < 3; j++){
                int xx = x + dir_x[i][j];
                int yy = y + dir_y[i][j];
                if(xx >= 0 && xx < n && yy >= 0 && yy < m){
                    if(mat[xx][yy] == '*'){
                        pos_x = xx; pos_y = yy;
                        cnt ++;
                    }
                }
                else{
                    ok = 0;
                    break;
                }
            }
            if(ok && cnt == 1){
                mat[pos_x][pos_y] = '.';
                q.push(make_pair(pos_x,pos_y));
            }
        }
        //input();
    }
    return;
}
int main(){
    while(~scanf("%d%d",&n,&m)){
        for(int i = 0; i < n; i++)
            scanf("%s",mat[i]);
        bfs();
        input();
    }
    return 0;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值