크기가 nxn인 행렬로 주어진 행렬의 모든 유형을 대각 행렬로 변환하는 작업입니다.
대각 행렬이란 무엇입니까
대각 행렬은 모든 비대각 요소가 0이고 대각 요소가 임의의 값이 될 수 있는 nxn 행렬입니다.
아래는 대각선이 아닌 요소를 0으로 변환하는 다이어그램입니다.
$$\begin{bmatrix}1 &2 &3 \\4 &5 &6 \\7 &8 &9 \end{bmatrix}\:\rightarrow\:\begin{bmatrix}1 &0 &3 \\0 &5 &0 \\7 &0 &9 \end{bmatrix}$$
접근 방식은 모든 비대각선 요소에 대해 하나의 루프를 시작하고 대각선 요소에 대해 다른 루프를 시작하고 비대각선의 값을 0으로 바꾸고 대각선 요소를 변경하지 않은 상태로 두는 것입니다.
예시
Input-: matrix[3][3] = {{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }}
Output-: {{ 1, 0, 3},
{ 0, 5, 0},
{ 7, 0, 9}}
Input-: matrix[3][3] = {{ 91, 32, 23 },
{ 40, 51, 26 },
{ 72, 81, 93 }}
Output-: {{ 91, 0, 23},
{ 0, 51, 0},
{ 72, 0, 93}} 알고리즘
Start
Step 1-> define macro for matrix size as const int n = 10
Step 2-> Declare function for converting to diagonal matrix
void diagonal(int arr[][n], int a, int m)
Loop For int i = 0 i < a i++
Loop For int j = 0 j < m j++
IF i != j & i + j + 1 != a
Set arr[i][j] = 0
End
End
End
Loop For int i = 0 i < a i++
Loop For int j = 0 j < m j++
Print arr[i][j]
End
Print \n
End
Step 2-> In main()
Declare matrix as int arr[][n] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } }
Call function as diagonal(arr, 3, 3)
Stop 예시
#include <iostream>
using namespace std;
const int n = 10;
//print 0 at diagonals in matrix of nxn
void diagonal(int arr[][n], int a, int m) {
for (int i = 0; i < a; i++) {
for (int j = 0; j < m; j++) {
if (i != j && i + j + 1 != a)
arr[i][j] = 0;
}
}
for (int i = 0; i < a; i++) {
for (int j = 0; j < m; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
int main() {
int arr[][n] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
diagonal(arr, 3, 3);
return 0;
} 출력
위의 코드를 실행하면 다음 출력이 생성됩니다.
0 2 0 4 0 6 0 8 0