Guest User

Untitled

a guest
Jun 23rd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. package com.sangmoon.square;
  2.  
  3. public class Square {
  4.  
  5. public static void main(String arg[]){
  6. int N = Integer.parseInt(arg[0]);
  7. int[][] map = new int[N][N];
  8.  
  9. Square s = new Square();
  10.  
  11. s.solve(0, 0, map, 1, N);
  12.  
  13. for (int i=0; i< N; i++){
  14. for (int j =0; j<N; j++){
  15. System.out.format("%02d ", map[i][j]);
  16. }
  17. System.out.println();
  18. }
  19. }
  20.  
  21. public void solve(int startX, int startY, int[][] map, int k, int n){
  22.  
  23. int posX = startX;
  24. int posY = startY;
  25. int idx = 1;
  26.  
  27. map[posX][posY] = k;
  28. if (n == 1)
  29. return;
  30.  
  31. idx++;
  32. k++;
  33.  
  34. Direction d = Direction.RIGHT;
  35.  
  36. Counter c = new Counter(n-1);
  37.  
  38.  
  39. while(idx <= 4*n -4){
  40. posX += d.getX();
  41. posY += d.getY();
  42.  
  43. map[posX][posY] = k;
  44. idx++;
  45. k++;
  46.  
  47. c.count();
  48. if (c.getCount() == n - 1){
  49. switch (d){
  50. case RIGHT:
  51. d = Direction.DOWN;
  52. break;
  53. case DOWN:
  54. d = Direction.LEFT;
  55. break;
  56. case LEFT:
  57. d = Direction.UP;
  58. break;
  59. default:
  60. System.out.println("nonono");
  61. }
  62. }
  63. }
  64.  
  65. if ( n == 2 ){
  66. return;
  67. } else {
  68. solve(posX, posY +1, map, k, n -2 );
  69. }
  70.  
  71.  
  72. }
  73. }
  74.  
  75. enum Direction {
  76. RIGHT(0, 1), LEFT(0, -1), DOWN(1, 0), UP(-1, 0);
  77.  
  78. public int getX() {
  79. return x;
  80. }
  81.  
  82. public int getY() {
  83. return y;
  84. }
  85.  
  86. private int x;
  87. private int y;
  88.  
  89. Direction(int x, int y){
  90. this.x = x;
  91. this.y = y;
  92. }
  93. }
  94.  
  95. class Counter{
  96. private int initCount;
  97. private int count;
  98.  
  99. Counter(int n){
  100. initCount = n;
  101. count = n;
  102. }
  103.  
  104. public void count(){
  105. count --;
  106. if (count == 0)
  107. count = initCount;
  108. return;
  109. }
  110.  
  111. public int getCount(){
  112. return count;
  113. }
  114. }
Add Comment
Please, Sign In to add comment