본문 바로가기
Algorithm 💫/Problem Solving

[백준] 17086번: 아기상어 2 / C++

by 돼지고기맛있다 2021. 9. 17.
반응형

✏️ 문제 링크

https://www.acmicpc.net/problem/17086

 

17086번: 아기 상어 2

첫째 줄에 공간의 크기 N과 M(2 ≤ N, M ≤ 50)이 주어진다. 둘째 줄부터 N개의 줄에 공간의 상태가 주어지며, 0은 빈 칸, 1은 아기 상어가 있는 칸이다. 빈 칸의 개수가 한 개 이상인 입력만 주어진다.

www.acmicpc.net

 

 

✏️ 문제 설명 (더보기 클릭 👆🏻)

 

✏️ 문제 코드

#include <bits/stdc++.h>

using namespace std;
using pii=pair<int, int>;

#define MAX 51

typedef struct Node{
    int x, y; long cnt;
}Node;

int dx[]={-1,1,1,-1,-1,1,0,0};
int dy[]={1,1,-1,-1,0,0,-1,1};

int bfs(int cx, int cy){
    int r=98765432;
    bool vis[MAX][MAX]; 
    for(int i=0; i<N; i++){
        for(int j=0; j<M; j++){
            vis[i][j]=false;
        }
    }
    queue<Node> q; q.push({cx, cy, 0}); vis[cx][cy]=true;
    while(!q.empty()){
        Node cur=q.front(); q.pop();
        int x=cur.x; int y=cur.y; int c=cur.cnt;
        if(m[x][y]==1){
           return c;
        }
        for(int i=0; i<8; i++){
            int nx=x+dx[i]; int ny=y+dy[i];
            if(nx<0 || nx>=N || ny<0 || ny>=M || vis[nx][ny]) continue;
            q.push({nx, ny, c+1});
            vis[nx][ny]=true;
        }
    }
}
int main(){
    int answer=0; cin>>N>>M;
    
    for(int i=0; i<N; i++){
        for(int j=0; j<M; j++){
            cin>>m[i][j];
        }
    }
    
    for(int i=0; i<N; i++){
        for(int j=0; j<M; j++){
            if(m[i][j]==0){
                answer=max(answer, bfs(i, j));
            }
        }
    }
    
    cout<<answer<<"\n";
    
    return 0;
}

 

 

 

 ⭐ if feedback and question : comment please⭐  

 

 

 

 

 

반응형

댓글