12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- #include <iostream>
- void cyclic_shift(int**& matrix, int rows, int cols, const std::string& direction, int shift_count, bool rows_shift, bool cols_shift) {
- if (rows_shift) {
- shift_count %= rows;
- int** temp = new int*[rows];
- for (int i = 0; i < rows; ++i) {
- temp[i] = new int[cols];
- }
- if (direction == "up") {
- for (int i = 0; i < rows; ++i) {
- std::copy(matrix[(i + shift_count) % rows], matrix[(i + shift_count) % rows] + cols, temp[i]);
- }
- } else if (direction == "down") {
- for (int i = 0; i < rows; ++i) {
- std::copy(matrix[(i - shift_count + rows) % rows], matrix[(i - shift_count + rows) % rows] + cols, temp[i]);
- }
- }
- for (int i = 0; i < rows; ++i) {
- delete[] matrix[i];
- }
- delete[] matrix;
- matrix = temp;
- }
- if (cols_shift) {
- shift_count %= cols;
- for (int i = 0; i < rows; ++i) {
- if (direction == "right") {
- int* temp = new int[cols];
- for (int j = 0; j < cols; ++j) {
- temp[j] = matrix[i][(j - shift_count + cols) % cols];
- }
- std::copy(temp, temp + cols, matrix[i]);
- delete[] temp;
- } else if (direction == "left") {
- int* temp = new int[cols];
- for (int j = 0; j < cols; ++j) {
- temp[j] = matrix[i][(j + shift_count) % cols];
- }
- std::copy(temp, temp + cols, matrix[i]);
- delete[] temp;
- }
- }
- }
- }
- int main() {
- int rows = 3, cols = 3;
- int** matrix = new int*[rows];
- for (int i = 0; i < rows; ++i) {
- matrix[i] = new int[cols];
- }
- matrix[0][0] = 1; matrix[0][1] = 2; matrix[0][2] = 3;
- matrix[1][0] = 4; matrix[1][1] = 5; matrix[1][2] = 6;
- matrix[2][0] = 7; matrix[2][1] = 8; matrix[2][2] = 9;
- std::string direction = "right";
- int shift_count = 1;
- cyclic_shift(matrix, rows, cols, direction, shift_count, false, true);
- for (int i = 0; i < rows; ++i) {
- for (int j = 0; j < cols; ++j) {
- std::cout << matrix[i][j] << " ";
- }
- std::cout << std::endl;
- }
- for (int i = 0; i < rows; ++i) {
- delete[] matrix[i];
- }
- delete[] matrix;
- return 0;
- }
|