Skip to content

Commit

Permalink
Spiral array (#927)
Browse files Browse the repository at this point in the history
* Added new spiral Array algorithm

* Changes in readme.md

* Added Sample input/ouput in readme.md

* renamed readme.md to README.md

* Added sample I/O and spacing changes

* Added sample I/O and spacing changes
  • Loading branch information
vishnu0179 authored and GOVINDDIXIT committed Apr 10, 2019
1 parent 4225c06 commit a6f7c00
Show file tree
Hide file tree
Showing 2 changed files with 123 additions and 0 deletions.
37 changes: 37 additions & 0 deletions Spiral_Array/README.md
@@ -0,0 +1,37 @@
# Spiral Array

Spiral Array Algorithm traverses an array in a spiral order.

## Example

![Spiral Array](http://1.bp.blogspot.com/-CD9C_7oeI3I/VgwL3AO-IeI/AAAAAAAACBc/EG-WAf-y_7E/s1600/spiral-circular-matrix.jpg)

## Algorithm

```
Step-1 : Traverse the topmost row of array in left to right.
Step-2 : Increment the top variable.
Step-3 : Traverse the rightmost column of array from top to bottom.
Step-4 : Decrement the right variable.
Step-5 : Traverse the bottommost row of array from right to left.
Step-6 : Decrement the bottom variable.
Step-7 : Traverse the leftmost row of array from bottom.
Step-8 : Increment the left variable.
```

## 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
```
86 changes: 86 additions & 0 deletions Spiral_Array/Spiral_Array.c
@@ -0,0 +1,86 @@
//SPIRAL PRINTING 2-D matrix

#include <stdio.h>

int main()
{
int m, n;
int left, right, top, bottom;
int i, j, count, dir;
int arr[100][100];

scanf("%d %d", &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++)
scanf("%d", &arr[i][j]);
}

while (left <= right && top <= bottom && count > 0)
{
if (dir == 1) //left to right
{
for (i = left; i <= right; i++)
{
printf("%d ", arr[top][i]); //Printing the topmost untraversed row
count--;
}
dir++;
top++;
}
if (dir == 2) //top to bottom
{
for (i = top; i <= bottom; i++)
{
printf("%d ", arr[i][right]); //Printing the rightmost untraversed column
count--;
}
dir++;
right--;
}
if (dir == 3) //left to right
{
for (i = right; i >= left; i--)
{
printf("%d ", arr[bottom][i]); //Printing the bottommost untraversed column
count--;
}
dir++;
bottom--;
}
if (dir == 4) //bottom to top
{
for (i = bottom; i >= top; i--)
{
printf("%d ", 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
*/

0 comments on commit a6f7c00

Please sign in to comment.