이 문제에서는 크기가 nXn인 정사각형 행렬이 제공됩니다. 우리의 임무는 정사각형 행렬 대각선에서 가장 작은 요소와 가장 큰 요소를 찾는 것입니다. 매트릭스의 1차 및 2차 대각선의 가장 작은 요소와 가장 큰 요소를 찾아야 합니다.
문제를 이해하기 위해 예를 들어보겠습니다.
입력
mat[][] = {
{3, 4, 7},
{5, 2, 1},
{1, 8, 6}
} 출력
Smallest element in Primary Diagonal = 2 Largest element in Primary Diagonal = 6 Smallest element in Secondary Diagonal = 1 Largest element in Secondary Diagonal = 7
해결 방법
문제를 해결하는 간단한 솔루션은 중첩 루프를 사용하는 것입니다. 기본 대각선에서 요소를 확인하기 위해 i =j를 고려할 것입니다. . 그리고 2차 대각선의 경우 i + j =n -1을 고려합니다. . 1차 및 2차 대각 행렬의 최대 및 최소 요소를 찾습니다.
우리 솔루션의 작동을 설명하는 프로그램
예
#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 : 2 Greatest 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 : 2 Greatest Element of Principal Diagonal : 8 Smallest Element of Secondary Diagonal : 1 Greatest Element of Secondary Diagonal : 7