codeforces 1182B (DFS)

題意描述

You have a given picture with size w×h. Determine if the given picture has a single “+” shape or not. A “+” shape is described below:

  • A “+” shape has one center nonempty cell.
  • There should be some (at least one) consecutive non-empty cells in each direction (left, right, up, down) from the center. In other words, there should be a ray in each direction.
  • There should be some (at least one) consecutive non-empty cells in each direction (left, right, up, down) from the center. In other words, there should be a ray in each direction.

Find out if the given picture has single “+” shape.

給你一串字符,讓你判斷所有的*是否可以構成唯一的+號

思路

我們可以先找到構成加號中間的星號,然後分別向四個方向dfs,dfs的過程中統計星號的個數,最後判斷一下dfs星號的個數是否與所有星號的個數相同即可。

AC代碼

#include<bits/stdc++.h>
#define x first
#define y second
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long LL;
const int N=2*1e5+10;
const int M=150;
const int INF=0x3f3f3f3f;
const int MOD=998244353;
int n,m;
char g[505][505];
int dx[4]={1,-1,0,0},dy[4]={0,0,1,-1};
bool st[505][505];
int deg=0;
void dfs(int x,int y,int dir){
    //cout<<x<<' '<<y<<endl;
    if(g[x][y]=='.') return ;
    if(x<0 || y<0 || x>=n || y>=m) return ;

    if(!st[x][y]) deg++;
    st[x][y]=true;

    dfs(x+dx[dir],y+dy[dir],dir);
}
void solve(){
    cin>>n>>m;
    for(int i=0;i<n;i++) cin>>g[i];
    int cnt=0,sum=0,sum_copy=0;
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            if(g[i][j]=='*') sum++;
        }
    }
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            if(i>=1 && j>=1 && i+1<n && j+1<m){
                if(g[i][j]=='*' && g[i-1][j]=='*' && g[i+1][j]=='*' && g[i][j+1]=='*' && g[i][j-1]=='*'){
                    dfs(i,j,0);
                    dfs(i,j,1);
                    dfs(i,j,2);
                    dfs(i,j,3);
                    cnt++;
                }
            }
        }
    }
    //cout<<cnt<<' '<<deg<<endl;
    if(cnt!=1 || deg!=sum) cout<<"No"<<endl;
    else cout<<"YES"<<endl;
}
int main(){
    IOS;
    solve();
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章