-
Notifications
You must be signed in to change notification settings - Fork 0
/
Boundary traversal of matrix
60 lines (47 loc) · 1.26 KB
/
Boundary traversal of matrix
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
60
//User function Template for Java
class Solution
{
//Function to return list of integers that form the boundary
//traversal of the matrix in a clockwise manner.
static ArrayList<Integer> boundaryTraversal(int matrix[][], int n, int m)
{
// code here
ArrayList<Integer> result = new ArrayList<Integer>();
if(n == 1)
{
int i = 0;
while(i < m)
{
result.add(matrix[0][i++]);
}
}
else if(m == 1)
{
int i = 0;
while(i < n)
{
result.add(matrix[i++][0]);
}
}
else
{
for(int j=0;j<m;j++)
{
result.add(matrix[0][j]);
}
for(int j=1;j<n;j++)
{
result.add(matrix[j][m-1]);
}
for(int j=m-2;j>=0;j--)
{
result.add(matrix[n-1][j]);
}
for(int j=n-2;j>=1;j--)
{
result.add(matrix[j][0]);
}
}
return result;
}
}