Advertisement
nguyenan1197

Xoay Ma trận 3x3 theo chiều kim đồng hồ 1 góc 90 độ

Feb 28th, 2020
649
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. #define N 3 //Khai báo cấp ma trận
  6.  
  7. //Hàm xoay ma trận
  8. void xoayMaTran(int a[N][N])
  9. {
  10.  
  11.     //Chạy qua từng chu kỳ
  12.     for (int i = 0; i < N / 2; i++) {
  13.         for (int j = i; j < N - i - 1; j++) {
  14.  
  15.             //Hoán vị từng phần tử theo từng chu kỳ
  16.             int temp = a[i][j];
  17.             a[i][j] = a[N - 1 - j][i];
  18.             a[N - 1 - j][i] = a[N - 1 - i][N - 1 - j];
  19.             a[N - 1 - i][N - 1 - j] = a[j][N - 1 - i];
  20.             a[j][N - 1 - i] = temp;
  21.         }
  22.     }
  23. }
  24. //Hàm nhập ma trận
  25. void nhapMaTran(int arr[N][N])
  26. {
  27.     for (int i = 0; i < N; i++) {
  28.         for (int j = 0; j < N; j++)
  29.         {
  30.             cout << "\nNhap arr[" << i << "][" << j << "] = ";
  31.             cin >> arr[i][j];
  32.         }
  33.         cout << '\n';
  34.     }
  35. }
  36.  
  37. //Hàm xuất ma trận
  38. void xuatMaTran(int arr[N][N])
  39. {
  40.     for (int i = 0; i < N; i++) {
  41.         for (int j = 0; j < N; j++)
  42.         {
  43.             cout << arr[i][j] << "\t";
  44.         }
  45.         cout << "\n\n";
  46.     }
  47. }
  48.  
  49. int main()
  50. {
  51.     int arr[N][N];
  52.     cout << "\n------------- NHAP MA TRAN -------------\n";
  53.     nhapMaTran(arr); //nhập phần tử
  54.     system("cls");
  55.     cout << "\n------------- MA TRAN DA NHAP -------------\n\n";
  56.     xuatMaTran(arr);
  57.     xoayMaTran(arr); //xử lý xoay ma trận
  58.     cout << "\n------------- MA TRAN BI XOAY -------------\n\n";
  59.     xuatMaTran(arr);
  60.     system("pause");
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement