백준 14716 c++

magicdrill·2024년 3월 23일

백준 문제풀이

목록 보기
196/673

백준 14716 c++

간단한 BFS문제이다.
방향이 8방향으로 늘어난 걸 제외하면 평범한 BFS 문제이다.

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

vector <vector<int>> board;
vector <vector<bool>> visited;
vector<pair<int, int>>direction{ {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1} };
int M, N;

void input_friend()
{
	int i, j;

	cin >> M >> N;
	board.resize(M, vector<int>(N));
	visited.resize(M, vector<bool>(N, false));
	for (i = 0; i < M; i++)
	{
		for (j = 0; j < N; j++)
		{
			cin >> board[i][j];
		}
	}

	return;
}

void BFS(int start_y, int start_x)
{
	int i;
	int current_x, current_y, next_x, next_y;
	queue <pair<int, int>> q;
	int d_size = direction.size();

	q.push({ start_x, start_y });
	visited[start_y][start_x] = true;
	while (!q.empty())
	{
		current_x = q.front().first;
		current_y = q.front().second;
		q.pop();
		for (i = 0; i < d_size; i++)
		{
			next_x = current_x + direction[i].first;
			next_y = current_y + direction[i].second;
			if ((next_x >= 0 && next_x < N) && (next_y >= 0 && next_y < M) 
				&& board[next_y][next_x] == 1 
				&& visited[next_y][next_x] == false)
			{
				q.push({ next_x, next_y });
				visited[next_y][next_x] = true;
			}
		}
	}

	return;
}

void find_answer()
{
	int i, j;
	int answer = 0;

	for (i = 0; i < M; i++)
	{
		for (j = 0; j < N; j++)
		{
			if (board[i][j] == 1 && visited[i][j] == false)
			{
				BFS(i, j);
				answer++;
			}
		}
	}
	cout << answer << "\n";

	return;
}

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

	input_friend();
	find_answer();

	return 0;
}

0개의 댓글