C++で周囲に最大数の星があるマトリックスでアルファベットを検索します
行列Mがあるとします。これは星と文字で埋められています。どの文字の周りに最大数の星があるかを見つける必要があります。したがって、行列が次のようになっている場合-
ここで、AとCの周りには7つの星があります。これは最大です。 Aは辞書式に小さいため、出力になります。
アプローチは簡単です。文字を数え、1人の文字が見つかったら、その周りの星を数えます。また、値をマップ内に保存します。印刷される最大サイズの地図から。
例
#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
-
C ++を使用して、マトリックス内の合計が最大の列を検索します。
サイズがMxNの行列があるとします。合計が最大の列を見つける必要があります。このプログラムでは、トリッキーなアプローチには従わず、配列を列ごとにトラバースし、各列の合計を取得します。合計が最大の場合は、合計と列インデックスを出力します。 例 #include<iostream> #define M 5 #define N 5 using namespace std; int colSum(int colIndex, int mat[M][N]){ int sum = 0; for(int i = 0; i<M; i++){
-
エッジのばらばらのパスの最大数を見つけるためのC++プログラム
これは、エッジの互いに素なパスの最大数を見つけるためのC ++プログラムです。これは、2つの頂点間の最短のサブセットパスまたは最大フローを意味します。 アルゴリズム: Begin function bfs() returns true if there is path from source s to sink t in the residual graph which indicates additional possible flow in the graph. End Begin fu