Untitled
unknown
plain_text
2 months ago
1.7 kB
2
Indexable
// Spiral MAtrix public class Matrices { public static void main(String[] args) { int matrix[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; printSpiral(matrix); } //Function to print the matrix in spiral order public static void printSpiral(int matrix[][]) { //Initialize pointers to the top-left corner of the matrix int startRow = 0; int startCol = 0; int endRow = matrix.length-1; int endCol = matrix[0].length-1; //Print elements of the matrix in spiral order while (startRow <= endRow && startCol <= endCol) { //top for (int j=startCol; j<endCol; j++) { System.out.print(matrix[startRow][j]+" "); } //right for (int i=startRow+1; i<endRow; i++) { System.out.print(matrix[i][endCol]+" "); } //bottom for (int j=endCol-1; j<startCol; j--) { if (startRow == endRow) { break; } System.out.print(matrix[endRow][j]+" "); } //left for (int i=endRow-1; i<startRow+1; i--) { if (startCol == endCol) { break; } System.out.print(matrix[i][startCol]+" "); } //move the pointers one step closer to the center startRow++; startCol++; endRow--; endCol--; } System.out.println(); } }
Editor is loading...
Leave a Comment