Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit db5a138

Browse files
authored
Create Spiral_Traversal_Of_Matrix.java
1 parent ccf8e28 commit db5a138

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import java.util.*;
2+
import java.lang.*;
3+
import java.io.*;
4+
class GFG{
5+
public static void main (String[] args){
6+
//code
7+
Scanner s = new Scanner(System.in);
8+
int t = s.nextInt();
9+
10+
while(t-- > 0){
11+
int rows = s.nextInt();
12+
int cols = s.nextInt();
13+
14+
int mat[][] = new int[rows][cols];
15+
16+
for(int i = 0 ; i < rows ; i++){
17+
for(int j = 0 ; j < cols ; j++){
18+
mat[i][j] = s.nextInt();
19+
}
20+
}
21+
22+
int startRow = 0, startCol = 0, endRow = rows-1, endCol = cols-1;
23+
while(startRow <= endRow && startCol <= endCol){
24+
for(int i = startCol ; i <= endCol ; i++){
25+
System.out.print(mat[startRow][i] + " ");
26+
}
27+
startRow++;
28+
29+
for(int i = startRow ; i <= endRow ; i++){
30+
System.out.print(mat[i][endCol] + " ");
31+
}
32+
endCol--;
33+
34+
if(startRow <= endRow){
35+
for(int i = endCol ; i >= startCol ; i--){
36+
System.out.print(mat[endRow][i] + " ");
37+
}
38+
endRow--;
39+
}
40+
if(startCol <= endCol){
41+
for(int i = endRow ; i >= startRow ; i--){
42+
System.out.print(mat[i][startCol] + " ");
43+
}
44+
startCol++;
45+
}
46+
}
47+
48+
System.out.println();
49+
}
50+
}
51+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /