Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to reverse N x N matrix in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <ctime>

#define ROWS 3
#define COLS 3

void print_matrix(const std::vector<std::vector<int>>& matrix) {
    for (const auto& row : matrix) {
        for (int elem : row) {
            std::cout << elem << "\t";
        }
        std::cout << std::endl;
    }
}

void reverse_matrix(std::vector<std::vector<int>>& matrix) {
    int rows = matrix.size();
    int cols = matrix[0].size();
    int counter = 0;

    for (int r = rows - 1, i = 0; i < rows; i++, r--) {
        for (int c = cols - 1, j = 0; j < cols; j++, c--) {
            std::swap(matrix[i][j], matrix[r][c]);
            counter++;
            if (counter > (rows * cols) / 2 - 1) return; // stop halfway
        }
    }
}

int main() {
    std::vector<std::vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

    std::cout << "Matrix 1:\n";
    print_matrix(matrix);
    
    reverse_matrix(matrix);
    std::cout << "Reversed Matrix 1:\n";
    print_matrix(matrix);

    srand(time(nullptr));
    for (auto& row : matrix) {
        for (int& elem : row) {
            elem = rand() % 10 + 1;
        }
    }

    std::cout << "\nMatrix 2:\n";
    print_matrix(matrix);
    
    reverse_matrix(matrix);
    std::cout << "Reversed Matrix 2:\n";
    print_matrix(matrix);

    return 0;
}



/*
run:

Matrix 1:
1	2	3	
4	5	6	
7	8	9	
Reversed Matrix 1:
9	8	7	
6	5	4	
3	2	1	

Matrix 2:
4	3	7	
3	5	6	
5	1	10	
Reversed Matrix 2:
10	1	5	
6	5	3	
7	3	4

*/

 



answered Apr 20, 2025 by avibootz
...