Cartography
Time limit3sMemory limit512 MB
Given possibly wrong neighbour lists for each house in an unknown r by c grid, find a grid layout that matches all lists or report -1.
- Level
Medium6 of 10
- Topics
- Graph, Implementation, Brute force
- Solved
- No attempts yet
Statement
Cartography is the practice of creating maps. Abbey is a cartographer who wants to draw a map of where every house is in a particular city. She has never visited that city.
The city is a rectangular grid with one house at each intersection. She does not know the dimensions of the grid, but she knows that each dimension is at least 2.
Neighbours are the houses exactly one intersection away from you in one of the four directions (north, east, south, west). Each house has exactly 2, 3, or 4 neighbours: 2 if the house is at a corner, 3 if it is on an edge, and 4 otherwise.
Last year, each household in the city wrote down who all of their neighbours were. Some of these census results may be incorrect. Some households reported the wrong person as a neighbour, some left out neighbours, some listed extra neighbours, and some even listed themselves as their own neighbour.
Help Abbey draw a map of the city that is consistent with all the census results, if possible. A map is consistent if every household wrote down exactly its neighbours.
Input
The first line contains a single integer (), the number of houses in the city.
The next lines describe the census results in order from house 1 to house . Each line starts with an integer (), the number of neighbours this house has, followed by distinct integers between 1 and , the house numbers of those neighbours.
Output
If there is no valid map consistent with the input, print -1.
Otherwise, print the dimensions and on the first line, then print an grid of integers. Each number from 1 to must appear exactly once, and the map must be consistent with the input. If multiple correct answers exist, any one is accepted.