private static int step(int dir, int rows, int cols, int[] dx, int[] dy, int[] xy, int[][] m) {
        dir++;
        if (dir > 3) {
            dir = 0;
        }
        final int xc = xy[0];
        final int yc = xy[1];
        int x = xc + dx[dir];
        int y = yc + dy[dir];
        int turns = 0;
        while ((x < 0 || x >= rows || y < 0 || y >= cols || m[x][y] > 0) && turns < 4) {
            turns++;
            dir--;
            if (dir < 0) {
                dir = 3;
            }
            x = xc + dx[dir];
            y = yc + dy[dir];
        }
        xy[0] = x;
        xy[1] = y;
        return dir;
    }