fork download
  1. import java.util.*;
  2. import java.lang.*;
  3.  
  4. class Main
  5. {
  6. static class Cycle {
  7. private int array[][];
  8. private int w,h;
  9. private ArrayList<int[]> path;
  10. private int startx,starty;
  11.  
  12. public Cycle(int array[][]) {
  13. this.array = array;
  14. this.h = array.length;
  15. this.w = array[0].length;
  16. }
  17.  
  18. public void start() {
  19. for (int y = 0; y < h; y++) {
  20. for (int x = 0; x < w; x++) {
  21. if (array[y][x] == 0) {
  22. int pos[] = {x,y};
  23. path = new ArrayList<int[]>();
  24. path.add(pos);
  25. startx = x;
  26. starty = y;
  27. follow(x, y, 1, 0);
  28. follow(x, y, -1, 0);
  29. follow(x, y, 0, 1);
  30. follow(x, y, 0, -1);
  31. }
  32. }
  33. }
  34. }
  35.  
  36. private void follow(int x, int y, int dx, int dy) {
  37. x += dx;
  38. y += dy;
  39. while (x >= 0 && x < w && y >= 0 && y < h) {
  40. if (x == startx && y == starty) {
  41. for (int[] pos : path) {
  42. System.out.printf("[%d,%d] ",pos[1], pos[0]);
  43. }
  44. System.out.printf("\n");
  45. break;
  46. }
  47. if (array[y][x] != 0) {
  48. int pos[] = {x,y};
  49. path.add(pos);
  50. if (dx != 0) {
  51. follow(x, y, 0, 1);
  52. follow(x, y, 0, -1);
  53. }
  54. else {
  55. follow(x, y, 1, 0);
  56. follow(x, y, -1, 0);
  57. }
  58. path.remove(path.size()-1);
  59. }
  60. x += dx;
  61. y += dy;
  62. }
  63. }
  64. }
  65.  
  66. public static void main (String[] args) throws java.lang.Exception
  67. {
  68. int array[][] = {
  69. {0,0,0,14},
  70. {0,10,0,0},
  71. {10,0,4,1},
  72. {0,5,7,0},
  73. {0,0,1,0}
  74. };
  75. Cycle cycle = new Cycle(array);
  76. cycle.start();
  77. }
  78. }
Success #stdin #stdout 0.09s 380224KB
stdin
Standard input is empty
stdout
[0,0] [0,3] [2,3] [2,0] 
[0,0] [2,0] [2,3] [0,3] 
[0,1] [0,3] [2,3] [2,2] [3,2] [3,1] 
[0,1] [3,1] [3,2] [2,2] [2,3] [0,3] 
[0,2] [0,3] [2,3] [2,2] 
[0,2] [2,2] [2,3] [0,3] 
[1,0] [1,1] [3,1] [3,2] [2,2] [2,0] 
[1,0] [2,0] [2,2] [3,2] [3,1] [1,1] 
[1,2] [1,1] [3,1] [3,2] 
[1,2] [3,2] [3,1] [1,1] 
[1,3] [1,1] [3,1] [3,2] [2,2] [2,3] 
[1,3] [2,3] [2,2] [3,2] [3,1] [1,1] 
[2,1] [2,2] [3,2] [3,1] 
[2,1] [3,1] [3,2] [2,2] 
[3,0] [3,2] [2,2] [2,0] 
[3,0] [2,0] [2,2] [3,2] 
[3,3] [3,2] [2,2] [2,3] 
[3,3] [2,3] [2,2] [3,2] 
[4,0] [4,2] [2,2] [2,0] 
[4,0] [2,0] [2,2] [4,2] 
[4,1] [4,2] [3,2] [3,1] 
[4,1] [3,1] [3,2] [4,2] 
[4,3] [4,2] [2,2] [2,3] 
[4,3] [2,3] [2,2] [4,2]