สมมติว่าเรามีเมทริกซ์ 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