Untitled
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] + " "); } startRow++; // Move startRow down after printing top row // right for (int i = startRow; i <= endRow; i++) { System.out.print(matrix[i][endCol] + " "); } endCol--; // Move endCol left after printing right column // bottom if (startRow <= endRow) { // Check to avoid printing the same row twice for (int j = endCol; j >= startCol; j--) { System.out.print(matrix[endRow][j] + " "); } endRow--; // Move endRow up after printing bottom row } // left if (startCol <= endCol) { // Check to avoid printing the same column twice for (int i = endRow; i >= startRow; i--) { System.out.print(matrix[i][startCol] + " "); } startCol++; // Move startCol right after printing left column } } System.out.println(); } }
Leave a Comment