#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX 26
string map[MAX];
int n;
int cnt = 0;
int dx[4] = { -1, 1, 0, 0 };
int dy[4] = { 0, 0,-1,1 };
vector<int> v;
void dfs(int x, int y) {
map[x][y] = '0';
cnt++;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < n) {
if (map[nx][ny] == '1') {
dfs(nx, ny);
}
}
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> map[i];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (map[i][j] == '1') {
dfs(i, j);
v.push_back(cnt);
cnt = 0;
}
}
}
cout << v.size() << "\n";
sort(v.begin(), v.end());
for (int i = 0; i < v.size(); i++) {
cout << v[i] << "\n";
}
}
💡 string으로 받아오므로 문자와 비교하기
#include <iostream>
#include <string.h>
using namespace std;
#define MAX 51
int map[MAX][MAX] = { 0, };
bool visited[MAX][MAX] = { false, };
int T, M, N, K;
//int n;
int cnt = 0;
int dx[4] = { -1, 1, 0, 0 };
int dy[4] = { 0, 0,-1,1 };
void dfs(int x, int y) {
visited[x][y] = true;
//cnt++;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < N && ny >= 0 && ny < M) {
if (map[nx][ny] == 1 && !visited[nx][ny]) {
dfs(nx, ny);
}
}
}
}
int main() {
cin >> T;
while (T > 0) {
cnt = 0;
cin >> M >> N >> K;
for (int i = 0; i < K; i++) {
int a, b;
cin >> a >> b;
map[b][a] = 1;
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (map[i][j] == 1 && !visited[i][j]) {
dfs(i, j);
cnt++;
}
}
}
cout << cnt << "\n";
T--;
memset(visited, false, sizeof(visited));
memset(map, 0, sizeof(map));
}
}
💡 memset
배열 초기화를 위해 씀, memset(배열이름, 초기화할 값, 사이즈)#include <string.h>
를 써주어야 한다.