1

I've created an undirected graph and extracted all the possible cycles inside it. I want just the simple cycles because I'm creating polygons from them. The problem is that I don't find an algorithm of how to do it. The following graph generates 6 possible cycles listed below which is working as intended.

int[][] graph = {{1, 2}, {1, 6}, {1, 5}, {2, 6}, {2, 3}, {3, 7}, {7, 4}, {3, 4}, {5, 4}};

1,6,2
1,5,4,7,3,2
1,5,4,3,2
1,5,4,7,3,2,6
1,5,4,3,2,6
3,4,7

How do I extract only the simple cycles from here? I've tried with the following code that removes all the cycles that contains another smaller cycle but I'm aware that the logic here isn't what I want because the result was: 1,6,2 1,5,4,3,2 3,4,7 when it should be 1,6,2 1,5,4,7,3,2,6 3,4,7.

static void cleanMultiples() {
    Set<Integer> toRemove = new HashSet<>();
    for (int i = 0; i < cycles.size(); i++) {
        for (int j = 0; j < cycles.size(); j++) {
            if (j == i) {
                continue;
            }
            Set<Integer> s = new HashSet<>();
            for (int k = 0; k < cycles.get(i).length; k++) {
                s.add(cycles.get(i)[k]);
            }
            int p = s.size();
            for (int k = 0; k < cycles.get(j).length; k++) {
                s.add(cycles.get(j)[k]);
            }

            if (s.size() == p) {
                toRemove.add(i);
            }
        }
    }
    List<Integer> list = new LinkedList<>(toRemove);
    Collections.sort(list);
    Collections.reverse(list);
    list.forEach((t) -> {
        cycles.remove(t.intValue());
    });
    if(!toRemove.isEmpty()){
        cleanMultiples();
    }
}

enter image description here

Teh Swish
  • 99
  • 1
  • 12
  • How do you define simple cycles? – risingStark Apr 13 '21 at 21:45
  • I dont see why your expected output excludes both `1,5,4,3,2` and `1,5,4,3,2,6`. There are 2 cycles with a 7 in the 4th position and 2 cycles with a 3 in the 4th position. I believe what you want to do is to remove cycles which are a subset of other cycles. In which case, the expected result should be `1,6,2 1,5,4,7,3,2,6 1,5,4,3,2,6 3,4,7` – Michael Apr 13 '21 at 21:55
  • @Michael why would I want `1,5,4,3,2,6` ? Think of this like each closed area is a city. In the picture, there are 3 closed areas that doesn't overlap eachother which is the ones I mentioned. – Teh Swish Apr 13 '21 at 22:11
  • 1
    That's just the way you've drawn it. There is nothing in the data which says they don't overlap, and so there is no information a computer could use to make that decision. What if 6 and 7 were swapped places but kept their same relations? https://imgur.com/jPnw1Th – Michael Apr 13 '21 at 22:24

0 Answers0