Created
November 19, 2016 04:18
-
-
Save gooooloo/6811c9865ee0fcf035e1f700cf5d0fea to your computer and use it in GitHub Desktop.
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 Untitled { | |
public static void main(String[] args) { | |
final int N = 9; | |
int[][] a = new int[N][N]; | |
int x = -1; int y = 0; | |
int dx = 0; int dy = -1; | |
int k = 1; | |
while (true) { | |
// rotate direction | |
if (dx == 0 && dy == -1) { dx = 1; dy = 0; } | |
else if (dx == 1 && dy == 0) { dx = 0; dy = 1; } | |
else if (dx == 0 && dy == 1) { dx = -1; dy = 0; } | |
else { dx = 0; dy = -1; } | |
// move 1 step | |
x += dx; y+= dy; | |
if (a[x][y] != 0) { break; } | |
else { a[x][y] = k++;} | |
// move more steps | |
while(true) { | |
int nx = x + dx; int ny = y + dy; | |
if (nx < 0 || nx >= N || ny < 0 || ny >= N) { break; } | |
if (a[nx][ny] != 0) { break; } | |
x = nx; y = ny; | |
a[x][y] = k++; | |
} | |
} | |
for (int i = 0; i < N; i ++) { | |
for (int j = 0; j < N; j++) { | |
System.out.print(String.format("%3d", a[i][j])); | |
System.out.print(' '); | |
} | |
System.out.println(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment