Skip to content

Commit 1d0ba17

Browse files
committed
Read me
1 parent 82b8189 commit 1d0ba17

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/algorithms/2darray/README.md

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
Spiral Matrix Printing
2+
This is a Java program that prints a given matrix in a spiral order. It follows a clockwise direction starting from the top-left corner and spirals inward until all elements of the matrix are printed.
3+
4+
Algorithm
5+
The program uses the following algorithm to print the matrix in a spiral order:
6+
7+
Initialize variables to keep track of the boundaries of the matrix: startrow (starting row), endrow (ending row), startcol (starting column), and endcol (ending column).
8+
Use a while loop to iterate while the starting row is less than or equal to the ending row and the starting column is less than or equal to the ending column.
9+
Print the top boundary of the matrix by iterating from the starting column to the ending column of the current row.
10+
Print the rightmost column by iterating from the starting row + 1 to the ending row of the current column.
11+
Print the bottom boundary of the matrix by iterating from the ending column - 1 to the starting column. However, if the starting row is equal to the ending row, break the loop to avoid duplicating elements.
12+
Print the leftmost column by iterating from the ending row - 1 to the starting row + 1. Similarly, if the starting column is equal to the ending column, break the loop.
13+
Update the boundaries: increment the starting row, decrement the ending row, increment the starting column, and decrement the ending column.
14+
Repeat steps 3-7 until all elements of the matrix are printed.
15+
16+
17+
18+
19+
Usage
20+
To use the program, you need to have Java installed on your machine. Follow these steps:
21+
22+
Copy the code into a file named printspiral.java.
23+
24+
Open a command prompt or terminal and navigate to the directory where the printspiral.java file is saved.
25+
Compile the Java file by running the command: javac printspiral.java.
26+
Run the compiled program with the command: java printspiral.
27+
The program will print the given matrix in a spiral order. You can modify the matrix variable in the main function to test different matrices.
28+
29+
Example Output
30+
For the provided example matrix {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}}, the program will output:
31+
1 2 3 4
32+
8 12 16
33+
15 14 13
34+
9 5
35+
6 7
36+
11 10
37+
38+
39+
40+
This represents the spiral order of the matrix elements.
41+
42+
Feel free to modify the code and experiment with different matrices to observe the spiral printing pattern.

0 commit comments

Comments
 (0)