MCPcopy Create free account
hub / github.com/Manvityagi/PW-Skills-Java-Course-Codes / PrintSpiral

Class PrintSpiral

Lecture 22/src/PrintSpiral.java:3–66  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1import java.util.Scanner;
2
3public class PrintSpiral {
4 static void printMatrix(int[][] matrix){
5 for(int i = 0; i < matrix.length; i++){
6 for(int j = 0; j < matrix[i].length; j++){
7 System.out.print(matrix[i][j] + " ");
8 }
9 System.out.println();
10 }
11 }
12 static void printSpiralOrder(int[][] matrix, int r, int c){
13 int topRow = 0, bottomRow = r-1, leftCol = 0, rightCol = c-1;
14 int totalElements = 0;
15
16 while(totalElements < r * c){
17 // topRow -> leftCol to rightCol
18 for(int j = leftCol; j <= rightCol && totalElements < r*c; j++){
19 System.out.print(matrix[topRow][j] + " ");
20 totalElements++;
21 }
22 topRow++;
23
24 //rightCol -> topRow to BottomRow
25 for(int i = topRow; i <= bottomRow && totalElements < r*c; i++){
26 System.out.print(matrix[i][rightCol] + " ");
27 totalElements++;
28 }
29 rightCol--;
30
31 //bottomRow -> rightCol to leftCol
32 for(int j = rightCol; j >= leftCol && totalElements < r*c; j--){
33 System.out.print(matrix[bottomRow][j] + " ");
34 totalElements++;
35 }
36 bottomRow--;
37
38 //leftCol -> bottomRow to topRow
39 for(int i = bottomRow; i >= topRow && totalElements < r*c; i--){
40 System.out.print(matrix[i][leftCol] + " ");
41 totalElements++;
42 }
43 leftCol++;
44 }
45 }
46
47 public static void main(String[] args) {
48 Scanner sc = new Scanner(System.in);
49 System.out.println("Enter number of rows and columns of matrix");
50 int r = sc.nextInt();
51 int c = sc.nextInt();
52 int[][] matrix = new int[r][c];
53 int total = r * c;
54 System.out.println("Enter " + total + " values");
55 for (int i = 0; i < r; i++){
56 for(int j = 0; j < c; j++){
57 matrix[i][j] = sc.nextInt();
58 }
59 }
60 System.out.println("Input Matrix");

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected