ํค์๋ : ํ๋ฆผ.
#include <iostream>
using namespace std;
#include <vector>
#include <queue>
int n, m;
vector<vector<int>> v;
vector<vector<bool>> check;
int bfs(int _y, int _x)
{
vector<pair<int, int>> temp;
int num = 0;
queue<pair<int, int>> q;
q.push(make_pair(_y, _x));
check[_y][_x] = true;
// ์ํ์ข์ฐ
vector<pair<int, int>> dir =
{ {-1,0} ,{1,0} , {0,-1} , {0,1} };
while (!q.empty())
{
pair<int, int> curVer = q.front();
q.pop();
check[curVer.first][curVer.second] = true;
for (int i = 0; i < 4; ++i)
{
// 0์ผ ๊ฒฝ์ฐ์ ๋ฃ๊ณ ,
int nextY = curVer.first + dir[i].first;
int nextX = curVer.second + dir[i].second;
// ๋ฒ์ ์ฒดํฌ
if (nextY < 0 || nextY >= n
|| nextX < 0 || nextX >= m)
{
continue;
}
// ๋ฐฉ๋ฌธ ์ฒดํฌ
if (check[nextY][nextX] == true)
{
continue;
}
if (v[nextY][nextX] == 0)
{
q.push(make_pair(nextY, nextX));
check[nextY][nextX] = true;
}
else if(v[nextY][nextX] == 1)
{
++num;
v[nextY][nextX] = 0;
check[nextY][nextX] = true;
//vector์๋ค๊ฐ ๊ธฐ๋กํ๋ค์์ ์ข
๋ฃ ์ ์
// check ๋ณ์ ์๋ณตํ์.
temp.push_back(make_pair(nextY, nextX));
}
}
}
for (int i = 0; i < temp.size(); ++i)
{
int y = temp[i].first;
int x = temp[i].second;
check[y][x] = false;
}
return num;
}
int main()
{
// 1์ธ ๋ถ๋ถ์ ์ง์ฐ๊ณ
// ์ ๋ถ ์ง์ฐ๋ ๊ฒ์ด ์๋๋ผ.
// 0์ธ ๋ถ๋ถ ๋ถํฐ ์งํํด์ผ ํ๋ค.
// ๊ทธ๋ฌ๋ค๊ฐ ์ธ์ ํ ๋ถ๋ถ์์ 1 ๋ฐ๊ฒฌ ํ๋ฉด
// 0์ผ๋ก ๋ณ๊ฒฝํ๊ณ ๋ฐ์ณ ๋์ค๊ณ , ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ ํด๋น ์ํ์ค์์๋
// ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ๋๋ฉด ๋ค์ด๊ฐ์ง ๋ชปํ์.
// ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ๋ ์ ์ ์ ํตํด์๋ ์ธ์ ์ํ์ค ์งํ ๋ชปํ๊ฒ ๋ง์.
cin >> n >> m;
v.resize(n, vector<int>(m));
check.resize(n, vector<bool>(m, false));
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
cin >> v[i][j];
}
}
int num = 0;
int cnt = 0;
// ๋ถ๋ณ์ ๋ง๋ค์ด์ ์ด๋ฏธ ๋ค์ด๊ฐ ์ ์ ์ ๊ดํด์ ํ ํ์ ์๋ค.
// ์ฌ๋ฌ๋ฒ ์ํํ๋ ๊ฑฐ๋ฅผ ์ด์ค ํฌ๋ฌธ์ด๋ bfs
// ๋ถ๋ณ์ ์ฒดํฌํ๋ ๋ฐฉ์์ผ๋ก ๋ค์ด๊ฐ๋ฉด ์นด์ดํ
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
if (check[i][j] == false)
{
num = bfs(i, j);
if (num != 0)
{
++cnt;
cout << num << endl;
}
}
}
}
cout << "result" << " ";
cout << cnt;
//cout << bfs(0, 0);
}
-> ์ด ์ฝ๋๋ก ํ๋ฉด , ๋ฐฉ๋ฌธ ์ฒดํฌ๋ก ์ธํด
์ถ๋ ฅํ๋ฉด
์๋์ฒ๋ผ ๋์ค๋๋ฐ 4 , 20 , 3์ด ์๋ฏธํ๋ ๊ฒ์ ๋ฐ๋ก ์์ 2๋ฒ์งธ ๊ทธ๋ํ๋ฅผ
ํ๋ฒ์ ํ์ํ๋ ๊ฒ์ด ์๋๋ผ....
-> ์ด๊ฒ์ฒ๋ผ ๋๋ ์ ํ์ ํ๊ฑฐ๋ค.
: ๊ฒ์ ์์ ๋น์ด์๋ ๋ถ๋ถ๊น์ง ํ๋ฒ์ ์งํํ ๊ฒ์ด๋ค.
์ด๋ค ์๊ฐ์ด ์๋ชป๋์๋ค๋ฉด , ๋ฐฉ๋ฌธ์ฒดํฌ๋ ์ค๋ก์ง bfs๋ง ์งํํด์ผ ํ๋ค.
: ์๋ํ๋ฉด 2๋ฒ์งธ bfs ๋๋, ์ฌ๊ธฐ์ ๋ฐ๋ก ๋ฐ์ณ ๋์ค๊ฒ ๋๋ค.
https://www.acmicpc.net/source/share/918889c66f1c4ace9ed54fbfccd2c20b
1) ๋ฒ : ํ์ด์ ๋ต์ผ๋ก ๋ถ๊ฐ๋ฅํ ๋
2) ๋ฒ : ๋ชจ๋ ์ปจํ ์ด๋์ ์์๋ฅผ ํ์ธํ๋ ๊ฒ์ด ์๋.