행렬 M이 있다고 가정합니다. 이것은 별과 문자로 채워져 있습니다. 우리는 어떤 글자가 그 주위에 가장 많은 별을 가지고 있는지 찾아야 합니다. 따라서 행렬이 아래와 같으면 -

여기서 A와 C는 주위에 7개의 별을 가지고 있습니다. 이것은 최대입니다. A는 사전순으로 더 작으므로 출력이 됩니다.
접근 방식은 간단합니다. 문자를 세고 한 문자가 발견되면 주변의 별을 세게 됩니다. 또한 맵 내부에 값을 저장합니다. 크기가 최대인 지도에서 인쇄됩니다.
예시
#include <iostream>
#include<unordered_map>
#define MAX 4
using namespace std;
int checkStarCount(int mat[][MAX], int i, int j, int n) {
int count = 0;
int move_row[] = { -1, -1, -1, 0, 0, 1, 1, 1 };
int move_col[] = { -1, 0, 1, -1, 1, -1, 0, 1 };
for (int k = 0; k < 8; k++) {
int x = i + move_row[k];
int y = j + move_col[k];
if (x >= 0 && x < n && y >= 0 && y < n && mat[x][y] == '*')
count++;
}
return count;
}
char charWithMaxStar(int mat[][4], int n) {
unordered_map<char, int> star_count_map;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ((mat[i][j] - 'A') >= 0 && (mat[i][j] - 'A') < 26) {
int stars = checkStarCount(mat, i, j, n);
star_count_map[mat[i][j]] = stars;
}
}
}
int max = -1;
char result = 'Z' + 1;
for (auto x : star_count_map) {
if (x.second > max || (x.second == max && x.first < result)) {
max = x.second;
result = x.first;
}
}
return result;
}
int main() {
int mat[][4] = {
{ 'B', '*', '*', '*' },
{ '*', '*', 'C', '*' },
{ '*', 'A', '*', '*' },
{ '*', '*', '*', 'D' }
};
int n = 4;
cout << charWithMaxStar(mat, n) << " has maximum amount of stars around it";
}
출력
A has maximum amount of stars around it