ด้วยเมทริกซ์ขนาด nxn ภารกิจเพื่อแปลงเมทริกซ์ที่กำหนดให้เป็นเมทริกซ์แนวทแยง
เมทริกซ์แนวทแยงคืออะไร
เมทริกซ์แนวทแยงคือเมทริกซ์ 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}$$
วิธีการคือเริ่มการวนรอบหนึ่งสำหรับองค์ประกอบที่ไม่เป็นแนวทแยงทั้งหมด และอีกหนึ่งการวนสำหรับองค์ประกอบในแนวทแยง และแทนที่ค่าขององค์ประกอบที่ไม่ใช่แนวทแยงด้วยศูนย์และปล่อยให้องค์ประกอบในแนวทแยงไม่เปลี่ยนแปลง
ตัวอย่าง
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