Skip to content

Instantly share code, notes, and snippets.

@gooooloo
Created November 19, 2016 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gooooloo/6811c9865ee0fcf035e1f700cf5d0fea to your computer and use it in GitHub Desktop.
Save gooooloo/6811c9865ee0fcf035e1f700cf5d0fea to your computer and use it in GitHub Desktop.
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