在 C++ 中从方阵对角线中找到最小和最大元素
在这个问题中,我们得到一个大小为 nXn 的方阵。我们的任务是从方阵对角线中找到最小和最大元素。我们需要找到矩阵的主要和次要对角线的最小和最大元素。
让我们举个例子来理解这个问题,
输入
mat[][] = {输出结果{3, 4, 7},
{5, 2, 1},
{1, 8, 6}
}
Smallest element in Primary Diagonal = 2Largest element in Primary Diagonal = 6
Smallest element in Secondary Diagonal = 1
Largest element in Secondary Diagonal = 7
解决方法
解决该问题的一个简单方法是使用嵌套循环。为了检查主对角线上的元素,我们将考虑i = j。对于次对角线,我们将考虑i + j = n -1。我们将为主对角线和次对角线找到矩阵的最大和最小元素。
程序来说明我们的解决方案的工作,
示例
#include<iostream>输出结果using namespace std;
void findMaxAndMinOfDiagonals(int mat[3][3], int n){
if (n == 0)
return;
int pDiagMin = mat[0][0],
pDiagMax = mat[0][0];
int sDiagMin = mat[0][n - 1 ],
sDiagMax = mat[0][n - 1];
for (int i = 1; i < n; i++) {
for (int j = 1; j < n; j++) {
if (i == j){
if (mat[i][j] < pDiagMin)
pDiagMin = mat[i][j];
if (mat[i][j] > pDiagMax)
pDiagMax = mat[i][j];
}
if ((i + j) == (n - 1)) {
if (mat[i][j] < sDiagMin){
sDiagMin = mat[i][j];
}
if (mat[i][j] > sDiagMax)
sDiagMax = mat[i][j];
}
}
}
cout<<("\nSmallest Element of Principal Diagonal : ")<<pDiagMin;
cout<<("\nGreatest Element of Principal Diagonal : ")<<pDiagMax;
cout<<("\nSmallest Element of Secondary Diagonal : ")<<sDiagMin;
cout<<("\nGreatest Element of Secondary Diagonal : ")<<sDiagMax;
}
int main(){
int mat[3][3] = {
{ 3, 4, 7 },
{ 0, 2, 1 },
{ 1, 7, 8 }
};
int n = sizeof(mat) / sizeof(mat[0]);
findMaxAndMinOfDiagonals(mat, n);
}
Smallest Element of Principal Diagonal : 2Greatest Element of Principal Diagonal : 8
Smallest Element of Secondary Diagonal : 2
Greatest Element of Secondary Diagonal : 7
另一个更有效的解决方案是使用以下事实将嵌套循环减少到单循环,即对于主对角线,垫子的索引是相同的,即
primary diagonal elements = mat[i][j].Similarly, for secondary diagonal elements = mat[i][n - i - 1]
程序来说明我们的解决方案的工作,
示例
#include<iostream>输出结果using namespace std;
void findMaxAndMinOfDiagonals(int mat[3][3], int n){
if (n == 0)
return;
int pDiagMin = mat[0][0],
pDiagMax = mat[0][0];
int sDiagMin = mat[0][n - 1 ],
sDiagMax = mat[0][n - 1];
for (int i = 1; i < n; i++) {
if (mat[i][i] < pDiagMin)
pDiagMin = mat[i][i];
if (mat[i][i] > pDiagMax)
pDiagMax = mat[i][i];
if (mat[i][n - 1 - i] < sDiagMin)
sDiagMin = mat[i][n - 1 - i];
if (mat[i][n - 1 - i] > sDiagMax)
sDiagMax = mat[i][n - 1 - i];
}
cout<<("\nSmallest Element of Principal Diagonal : ")<<pDiagMin;
cout<<("\nGreatest Element of Principal Diagonal : ")<<pDiagMax;
cout<<("\nSmallest Element of Secondary Diagonal : ")<<sDiagMin;
cout<<("\nGreatest Element of Secondary Diagonal : ")<<sDiagMax;
}
int main(){
int mat[3][3] = {
{ 3, 4, 7 },
{ 0, 2, 1 },
{ 1, 7, 8 }
};
int n = sizeof(mat) / sizeof(mat[0]);
findMaxAndMinOfDiagonals(mat, n);
}
Smallest Element of Principal Diagonal : 2Greatest Element of Principal Diagonal : 8
Smallest Element of Secondary Diagonal : 1
Greatest Element of Secondary Diagonal : 7
以上是 在 C++ 中从方阵对角线中找到最小和最大元素 的全部内容, 来源链接: utcz.com/z/359818.html