Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- #include<iostream>
- using namespace std;
- static const int DIRECTION_UP = 0;
- static const int DIRECTION_DOWN = 1;
- static const int DIRECTION_LEFT = 2;
- static const int DIRECTION_RIGHT = 3;
- int main()
- {
- int matrix[10][10], rows, columns;
- // Ask for matrix dimensions.
- cout << "Enter the amount of rows: ";
- cin >> rows;
- cout << "Enter the amount of columns: ";
- cin >> columns;
- // Ask for matrix elements.
- for (int row = 0; row < rows; row++)
- {
- cout << "Enter values for row " << (row + 1) << ": ";
- for (int column = 0; column < columns; column++)
- {
- cin >> matrix[row][column];
- }
- }
- // Define current movement direction in the matrix.
- int direction = DIRECTION_RIGHT;
- // Define current position in matrix.
- int currentRow = 0, currentColumn = 0;
- // Define valid boundaries of current position. Initially this spans the entire matrix
- // and will shrink in size during the spiral movement.
- int minColumn = 0, maxColumn = columns - 1;
- int minRow = 0, maxRow = rows - 1;
- // Perform spiral.
- for (int i = 0; i < rows*columns; i++)
- {
- // Print current element.
- cout << matrix[currentRow][currentColumn] << " ";
- // Move in current direction, and see for each case if we have to change direction and shrink the boundaries.
- switch (direction)
- {
- case DIRECTION_RIGHT:
- currentColumn++;
- if (currentColumn == maxColumn)
- {
- minRow++;
- direction = DIRECTION_DOWN;
- }
- break;
- case DIRECTION_DOWN:
- currentRow++;
- if (currentRow == maxRow)
- {
- maxColumn--;
- direction = DIRECTION_LEFT;
- }
- break;
- case DIRECTION_LEFT:
- currentColumn--;
- if (currentColumn == minColumn)
- {
- maxRow--;
- direction = DIRECTION_UP;
- }
- break;
- case DIRECTION_UP:
- currentRow--;
- if (currentRow == minRow)
- {
- minColumn++;
- direction = DIRECTION_RIGHT;
- }
- break;
- }
- }
- // Prevent from exiting.
- char x;
- cin >> x;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement