#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
queue<pair<int, int>> q;
int map[1000][250];
int ans, m, n;
int dx[8] = { -1,-1,-1,0,0,1,1,1 };
int dy[8] = { -1,0,1,-1,1,-1,0,1 };
void bfs(int x, int y) {
q.push({ x, y });
map[x][y] = 0;
while (!q.empty()) {
int a = q.front().first;
int b = q.front().second;
q.pop();
for (int i = 0; i < 8; i++) {
if (a + dx[i] >= 0 && a + dx[i] < m && b + dy[i] >= 0 && b + dy[i] < n
&& map[a + dx[i]][b + dy[i]] == 1) {
map[a + dx[i]][b + dy[i]] = 0;
q.push({ a + dx[i], b + dy[i] });
}
}
}
ans++;
return;
}
int main() {
cin >> m >> n;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> map[i][j];
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (map[i][j] == 1) {
bfs(i, j);
}
}
}
cout << ans;
return 0;
}
그냥 N*2의 모든 숫자들을 검색해서 최솟값을 찾는 것이 중요한 문제였는데 난 문자열로 바꾸어서 하나씩 비교해가며 찾는 잘못된 방식을 택하고 있었다.
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <algorithm>
using namespace std;
bool broken[10];
int check(int c) {
if (c == 0) {
if (broken[0]) {
return 0;
}
else {
return 1;
}
}
int len = 0;
while (c > 0) {
if (broken[c % 10]) {
return 0;
}
c = c / 10;
len += 1;
}
return len;
}
int main() {
int n, m, x;
cin >> n >> m;
for (int i = 0; i < m; i++) {
cin >> x;
broken[x] = true;
}
int result = abs(n - 100);
for (int i = 0; i <= 1000000; i++) {
int c = i;
int len = check(c);
if (len > 0) {
int press = abs(c - n);
if (result > press + len) {
result = press + len;
}
}
}
cout << result;
return 0;
}