1일1알

백준 1245번 농장 관리 C++ 본문

알고리즘

백준 1245번 농장 관리 C++

영춘권의달인 2022. 11. 3. 17:29

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

 

1245번: 농장 관리

첫째 줄에 정수 N(1 < N ≤ 100), M(1 < M ≤ 70)이 주어진다. 둘째 줄부터 N+1번째 줄까지 각 줄마다 격자의 높이를 의미하는 M개의 정수가 입력된다. 격자의 높이는 500보다 작거나 같은 음이 아닌 정수

www.acmicpc.net

 

bfs

 

#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <map>

using namespace std;

int n, m;

struct posInfo {
	int row;
	int col;
	int height;
};

int dRow[8] = { -1,-1,0,1,1, 1, 0,-1 };
int dCol[8] = { 0 , 1,1,1,0,-1,-1,-1 };

vector<vector<int>> board;
vector<vector<bool>> found;

int main()
{
	cin >> n >> m;
	board = vector<vector<int>>(n, vector<int>(m));
	found = vector<vector<bool>>(n, vector<bool>(m, false));
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cin >> board[i][j];
		}
	}
	queue<posInfo> q;
	int cnt = 0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (found[i][j]) continue;
			found[i][j] = true;
			q.push({ i,j,board[i][j] });
			bool ans = true;
			while (!q.empty()) {
				auto curr = q.front();
				q.pop();

				for (int k = 0; k < 8; k++) {
					int nextRow = curr.row + dRow[k];
					int nextCol = curr.col + dCol[k];
					if (nextRow < 0 || nextRow >= n) continue;
					if (nextCol < 0 || nextCol >= m) continue;
					if (board[nextRow][nextCol] > curr.height) {
						ans = false;
						continue;
					}
					if (found[nextRow][nextCol]) continue;
					if (board[nextRow][nextCol] < curr.height) continue;
					q.push({ nextRow,nextCol,curr.height });
					found[nextRow][nextCol] = true;
				}
			}
			if (ans) cnt++;
		}
	}
	cout << cnt;
}

'알고리즘' 카테고리의 다른 글

백준 20311번 화학 실험 C++  (0) 2022.11.05
백준 23351번 물 주기 C++  (0) 2022.11.04
백준 17178번 줄서기 C++  (0) 2022.11.02
백준 13905번 세부 C++  (0) 2022.10.31
백준 2109번 순회강연 C++  (0) 2022.10.30