Skip to content

Commit

Permalink
added spiral order in java
Browse files Browse the repository at this point in the history
  • Loading branch information
GauravWalia19 committed Apr 18, 2019
1 parent 8e29b93 commit e64c51f
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 0 deletions.
85 changes: 85 additions & 0 deletions Java/Data-Structures/ARRAYS/MISC/spiralOrder.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import java.util.*;
abstract class spiralOrder
{
/**
* SAMPLE TEST CASE
* 3 3
* 1 2 3
* 4 5 6
* 7 8 9
*
* OUTPUT
* 1
* 2
* 3
* 6
* 9
* 8
* 7
* 4
* 5
**/
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[][] arr = new int[n][m];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
arr[i][j] = in.nextInt();
}
}
printClock(arr,n,m);
in.close();
}

private static void printClock(int[][] arr,int n,int m)
{
int sr = 0;
int er = n;
int sc = 0;
int ec = m;

while(sr < er && sc < ec)
{
// l -> r
for(int i=sc;i<ec;i++)
{
System.out.println(arr[sr][i]);
}
sr++;

// |
// v
for(int i=sr;i<er;i++)
{
System.out.println(arr[i][ec-1]);
}
ec--;

//<-
if(sr<er)
{
for(int i=ec-1;i>=sc;i--)
{
System.out.println(arr[er-1][i]);
}
er--;
}

// ^
// |
if(sc<ec)
{
for(int i=er-1;i>=sr;i--)
{
System.out.println(arr[i][sc]);
}
sc++;
}
}
}
}
1 change: 1 addition & 0 deletions Java/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
* [ARRAYS CLASS](Data-Structures/ARRAYS/INBUILT/arrays.java)
* MISC
* JAGGED ARRAY
* [SPIRAL ORDER MATRIX](Data-Structures/ARRAYS/MISC/spiralOrder.java)

#### STRING

Expand Down
7 changes: 7 additions & 0 deletions datastructures.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,13 @@ Indexer for Data Structures Lover
* [C](C/Data-Structures/ARRAYS/MISC/jaggedarray.c)
* complexity

#### SPIRAL ORDER MATRIX

* blog/docs
* implementation
* [JAVA](Java/Data-Structures/ARRAYS/MISC/spiralOrder.java)
* complexity

## :octocat: STRING

* blog
Expand Down

0 comments on commit e64c51f

Please sign in to comment.