Created
September 5, 2024 22:43
-
-
Save c0debrain/588388faceabc91248485e26cedb2e6c to your computer and use it in GitHub Desktop.
print spiral matrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class App { | |
| public static void main(String[] args) { | |
| int n = 5; // input size | |
| int[][] matrix = new int[n][n]; | |
| int count = 1; | |
| int top = 0, bottom = n - 1, left = 0, right = n - 1; | |
| while (top <= bottom && left <= right) { | |
| // Print top row | |
| for (int i = left; i <= right; i++) { | |
| matrix[top][i] = count++; | |
| } | |
| top++; | |
| // Print right column | |
| for (int i = top; i <= bottom; i++) { | |
| matrix[i][right] = count++; | |
| } | |
| right--; | |
| // Print bottom row | |
| if (top <= bottom) { | |
| for (int i = right; i >= left; i--) { | |
| matrix[bottom][i] = count++; | |
| } | |
| bottom--; | |
| } | |
| // Print left column | |
| if (left <= right) { | |
| for (int i = bottom; i >= top; i--) { | |
| matrix[i][left] = count++; | |
| } | |
| left++; | |
| } | |
| } | |
| // Print the matrix | |
| for (int i = 0; i < n; i++) { | |
| for (int j = 0; j < n; j++) { | |
| System.out.printf("%2d ", matrix[i][j]); | |
| } | |
| System.out.println(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment