forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c572028
commit 0d8b570
Showing
1 changed file
with
83 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
// SPIRAL PRINTING 2-D matrix | ||
|
||
#include <iostream> | ||
using namespace std; | ||
|
||
int main() | ||
{ | ||
int m, n; | ||
int left, right, top, bottom; | ||
int i, j, count, dir; | ||
int arr[100][100]; | ||
|
||
cin >> m >> n; // Matrix of m*n | ||
|
||
left = 0; | ||
right = n-1; | ||
top = 0; | ||
bottom = m-1; | ||
|
||
count = m * n; // no. of elements | ||
dir = 1; | ||
|
||
for (i = 0; i < m; i++) // Taking Inputs | ||
{ | ||
for (j = 0; j < n; j++) | ||
cin >> arr[i][j]; | ||
} | ||
|
||
while (left <= right && top <= bottom && count > 0) | ||
{ | ||
if (dir == 1) // left to right | ||
{ | ||
for (i = left; i <= right; i++) | ||
{ | ||
cout << arr[top][i]; // Printing the topmost untraversed row | ||
count--; | ||
} | ||
dir++; | ||
top++; | ||
} | ||
if (dir == 2) //top to bottom | ||
{ | ||
for (i = top; i <= bottom; i++) | ||
{ | ||
cout << arr[i][right]; // Printing the rightmost untraversed column | ||
count--; | ||
} | ||
dir++; | ||
right--; | ||
} | ||
if (dir == 3) //left to right | ||
{ | ||
for (i = right; i >= left; i--) | ||
{ | ||
cout << arr[bottom][i]; // Printing the bottommost untraversed column | ||
count--; | ||
} | ||
dir++; | ||
bottom--; | ||
} | ||
if (dir == 4) // bottom to top | ||
{ | ||
for (i = bottom; i >= top; i--) | ||
{ | ||
cout << arr[i][left]; // Printing the leftmost untraversed column | ||
count--; | ||
} | ||
dir = 1; | ||
left++; | ||
} | ||
} | ||
return 0; | ||
} | ||
|
||
/* SAMPLE I/O | ||
Input | ||
3 3 | ||
1 2 3 | ||
4 5 6 | ||
7 8 9 | ||
Output | ||
1 2 3 6 9 8 7 4 5 | ||
*/ |