Search
Duplicate
📗

유기농 배추

주차
문제번호
1012
언어
C++
티어
실버
유형
그래프
BFS
DFS
nj_Blog
nj_상태
이해도
100%
풀이
사람
이해도 2
13 more properties

문제접근

놓쳤던 부분

전역변수 [51][51]로 할당해두고 fill 함수에서 [51][51]을 접근해버림

코드

2032 KB

0 ms

#include <iostream> #include <queue> #include <utility> #include <algorithm> using namespace std; int m,n; int board[51][51]; bool visited[51][51]; int dx[4] = {0, 1, 0, -1}; int dy[4] = {-1, 0, 1, 0}; void bfs(int y, int x) { queue<pair<int, int>> q; int cur_x; int cur_y; int next_x; int next_y; visited[y][x] = true; q.push({y, x}); while (!q.empty()) { cur_x = q.front().second; cur_y = q.front().first; q.pop(); for (int i = 0; i < 4; i++) { next_x = cur_x + dx[i]; next_y = cur_y + dy[i]; if (next_x < 0 || next_x >= m || next_y < 0 || next_y >= n) continue ; if (board[next_y][next_x] == 0 || visited[next_y][next_x]) continue ; visited[next_y][next_x] = true; q.push({next_y, next_x}); } } } int main(void) { int t, k; int x, y; int answer; ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> t; for (int i = 0; i < t; i++) { answer = 0; fill(&board[0][0], &board[50][50], 0); fill(&visited[0][0], &visited[50][50], 0); cin >> m >> n >> k; for (int j = 0; j < k; j++) { cin >> x >> y; board[y][x] = 1; } for (int j = 0; j < n; j++) { for (int l = 0; l < m; l++) { if (board[j][l] == 1 && !visited[j][l]) { bfs(j, l); answer++; } } } cout << answer << "\n"; } return (0); }
C++
복사