Find Poly

From programming_contest
Jump to navigation Jump to search

This problem gives us a set of edges and asks how many connected components there are, as well as which form a simple closed loop. Ignoring the input for one second we can find the number of connected components by choosing an unvisited vertex and doing BFS/Flood Fill to find all the visited vertices, and then repeating (after marking those vertices as visited). We can check that connected component forms a simply closed loop by ensuring that every vertex in that component is incident to exactly two edges.

From an implementation standpoint, we first need to read the input. Depending on the language, the easiest way may be to strip all whitespace, then split on the separator characters of ( , ) ; to get a stream of integers, which we can take four at a time. Instead of dealing with x,y pairs, we can map each vertex to a canonical ID by using 100*x+y (since 99 is the maximum value of either dimension). This allows us to form an undirected and unweighted adjacency list on which we can perform the other operations. In java, this is

HashMap<Integer, HashSet<Integer>>e=new HashMap<>();

One way to perform the actual algorithm is to create a HashSet of integers in each connected component using a BFS/Flood fill. Then in a second pass, we check whether there are 2 edges to that vertex in our adjacency list, and remove that node from said list.