-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiralPattern.java
61 lines (51 loc) · 1.02 KB
/
SpiralPattern.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.util.*;
class Spiral Pattern
{
static int R = 4;
static int C = 4;
static void print(int arr[][], int i, int j, int m, int n)
{
// If i or j lies outside the matrix
if (i >= m || j >= n)
{
return;
}
// Print First Row
for (int p = i; p < n; p++)
{
System.out.print(arr[i][p] + " ");
}
// Print Last Column
for (int p = i + 1; p < m; p++)
{
System.out.print(arr[p][n - 1] + " ");
}
// Print Last Row, if Last and
// First Row are not same
if ((m - 1) != i)
{
for (int p = n - 2; p >= j; p--)
{
System.out.print(arr[m - 1][p] + " ");
}
}
// Print First Column, if Last and
// First Column are not same
if ((n - 1) != j)
{
for (int p = m - 2; p > i; p--)
{
System.out.print(arr[p][j] + " ");
}
}
print(arr, i + 1, j + 1, m - 1, n - 1);
}
public static void main(String[] args)
{
int a[][] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
print(a, 0, 0, R, C);
}
}