線上性代數矩陣中查詢圍繞其有最多星星數量的字母


假設我們有一個矩陣 M。其中填滿星星和字母。我們需要找到哪個字母周圍有最多的星星。因此,如果矩陣如下所示 −

此處 A 和 C 周圍有 7 顆星星。這是最多的。由於 A 的字面量級較小,因此將輸出 A。

方法很簡單,我們將對字元進行計數,然後在找到一個字元後,再對它周圍的星星進行計數。此外,將值儲存在一個 map 中。選取大小最大的 map 輸出相應的值。

示例

 線上演示

#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

更新日期: 2020 年 1 月 3 日

143 次檢視

開啟你的 職業生涯

完成課程取得認證

開始
廣告