#include <iostream>
#include <vector>
using namespace std;
int main() {
int N = 4;
int M = 4;
vector<vector<int>> field = {
{1,1,0,0},
{0,1,0,1},
{0,0,0,1},
{1,0,0,0}
};
vector<vector<bool>> visited(N, vector<bool>(M, false));
int dx[4] = {-1,1,0,0};
int dy[4] = {0,0,-1,1};
int count = 0;
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
if(field[i][j] == 1 && !visited[i][j]){
count++; // 새로운 덩어리 시작
vector<pair<int,int>> stack;
stack.push_back({i,j});
visited[i][j] = true;
while(!stack.empty()){
pair<int,int> cur = stack.back();
stack.pop_back();
int x = cur.first;
int y = cur.second;
for(int k=0;k<4;k++){
int nx = x + dx[k];
int ny = y + dy[k];
if(nx>=0 && nx<N && ny>=0 && ny<M){
if(field[nx][ny]==1 && !visited[nx][ny]){
visited[nx][ny] = true;
stack.push_back({nx,ny});
}
}
}
}
}
}
}
cout << count << endl;
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: