import java.util.*; import java.lang.*; class Main { static class Cycle { private int array[][]; private int w,h; private ArrayList<int[]> path; private int startx,starty; public Cycle(int array[][]) { this.array = array; this.h = array.length; this.w = array[0].length; } public void start() { for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { if (array[y][x] == 0) { int pos[] = {x,y}; path = new ArrayList<int[]>(); path.add(pos); startx = x; starty = y; follow(x, y, 1, 0); follow(x, y, -1, 0); follow(x, y, 0, 1); follow(x, y, 0, -1); } } } } private void follow(int x, int y, int dx, int dy) { x += dx; y += dy; while (x >= 0 && x < w && y >= 0 && y < h) { if (x == startx && y == starty) { for (int[] pos : path) { } break; } if (array[y][x] != 0) { int pos[] = {x,y}; path.add(pos); if (dx != 0) { follow(x, y, 0, 1); follow(x, y, 0, -1); } else { follow(x, y, 1, 0); follow(x, y, -1, 0); } path.remove(path.size()-1); } x += dx; y += dy; } } } { int array[][] = { {0,0,0,14}, {0,10,0,0}, {10,0,4,1}, {0,5,7,0}, {0,0,1,0} }; Cycle cycle = new Cycle(array); cycle.start(); } }
Standard input is empty
[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]