[BOJ/C++] 4963 섬의 개수

GamzaTori·2025년 1월 18일

Algorithm

목록 보기
120/133

시간 복잡도

  • 인접 행렬을 이용한 BFS는 O(VE)O(V*E)의 시간 복잡도가 발생합니다.

문제 접근법

  • 섬의 상, 하, 좌, 우, 대각선 8방향을 탐색하며 이어져있는 섬을 탐색하는 문제입니다.
  • 섬을 인접 행렬로 초기화 한 뒤 모든 좌표에 대해 BFS를 수행합니다.
  • 아직 방문하지 않은 섬이 있다면 BFS로 탐색을 실행하고 섬의 개수를 카운트합니다.

코드

#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <string>
#include <climits>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>


using namespace std;

using int32 = long;
using int64 = long long;

static vector<vector<int>> G;
static vector<vector<int>> visited;

static int N=0, M = 0;

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

void BFS(int y, int x);

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);


    while(true)
    {
        int answer = 0;
        cin >> N >> M;

        if (N == 0 && M == 0)
            break;

        G = vector<vector<int>>(M, vector<int>(N, 0));
        visited = vector<vector<int>>(M, vector<int>(N, false));

        for (int i = 0; i < M; i++)
        {
            for (int j = 0; j < N; j++)
                cin >> G[i][j];
        }

        for(int i=0; i<M; i++)
        {
            for (int j = 0; j < N; j++)
            {
                if(!visited[i][j] && G[i][j])
                {
                    BFS(i, j);
                	answer++;
                }
            }
                
        }
        cout << answer << '\n';
    }


    return 0;
}

void BFS(int y, int x)
{
    visited[y][x] = true;
    queue<pair<int, int>> q;

    q.push({y, x});

    while(!q.empty())
    {
        int nowY = q.front().first;
        int nowX = q.front().second;

        q.pop();

        for(int i=0; i<8; i++)
        {
            int nextY = nowY + dy[i];
            int nextX = nowX + dx[i];
            
            if(nextY >=0 && nextY <M && nextX>=0 && nextX<N)
            {
                if(!visited[nextY][nextX] && G[nextY][nextX])
                {
                    visited[nextY][nextX] = true;
                    q.push({nextY, nextX});
                }
            }
        }
    }
}
profile
게임 개발 공부중입니다.

0개의 댓글