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

Appearance settings

Latest commit

 

History

History
History
64 lines (51 loc) · 1.81 KB

File metadata and controls

64 lines (51 loc) · 1.81 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
61
62
63
64
import java.util.Scanner;
public class Program41 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Taking matrix size input
System.out.print("Enter number of rows: ");
int rows = sc.nextInt();
System.out.print("Enter number of columns: ");
int cols = sc.nextInt();
int[][] matrix = new int[rows][cols];
// Taking matrix elements input
System.out.println("Enter the matrix elements:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = sc.nextInt();
}
}
System.out.println("Spiral Order Output:");
printSpiral(matrix, rows, cols);
}
public static void printSpiral(int[][] matrix, int rows, int cols) {
int top = 0, bottom = rows - 1;
int left = 0, right = cols - 1;
while (top <= bottom && left <= right) {
// Left to Right
for (int i = left; i <= right; i++) {
System.out.print(matrix[top][i] + " ");
}
top++;
// Top to Bottom
for (int i = top; i <= bottom; i++) {
System.out.print(matrix[i][right] + " ");
}
right--;
// Right to Left
if (top <= bottom) {
for (int i = right; i >= left; i--) {
System.out.print(matrix[bottom][i] + " ");
}
bottom--;
}
// Bottom to Top
if (left <= right) {
for (int i = bottom; i >= top; i--) {
System.out.print(matrix[i][left] + " ");
}
left++;
}
}
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.