JAVA
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class SpiralMatrix
{
private static int[][] spiral;
private static int w = 5, h = 5;
public static void main(String[] args)
{
System.out.println("List a simple SpiralMatrix:");
matrix(w, h);
display();
}
private static void matrix(int w, int h)
{
spiral = new int[w][h];
int value = 1, x = 0, y = 0;
while(true)
{
spiral[x][y] = value++;
boolean right = x < w-1 && spiral[x+1][y] == 0;
boolean down = y < h-1 && spiral[x][y+1] == 0;
boolean left = x > 0 && spiral[x-1][y] == 0;
boolean up = y > 0 && spiral[x][y-1] == 0;
if (right) if (up) y--; else x++;
else if (down) y++;
else if (left) x--;
else if (up) y--;
else break;
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run