Table of contents
Objective: Color each U.S. state so that no neighbouring states have the same colour.
Approach: We utilize backtracking and recursion to assign colours to states and backtracking when there is no valid colouring.
Validation Function (
is_valid_color
): This function checks if a particular colour could be assigned to a state, considering the colours of its neighbours.Recursive Coloring Function (
graph_coloring_util
): This function recursively tries to set colours to states. If assigning a colour leads to a solution, it continues or backtracks.Main Coloring Function (
graph_coloring
): Initializes the colour assignment list and calls the recursive colouring function.
Graph Representation
We represent the U.S. states and their neighbouring relationships as an adjacency matrix.
generate_graph
:Defines a list of U.S. states along with their neighbours.
Converts this relationship into an adjacency matrix representation.
Mapping and Visualization
This section is concerned with visualizing the colour assignment on the U.S. map.
Basemap setup: We use the Basemap toolkit to handle the map drawing. We specify the lower left and upper correct latitude and longitude to set the boundaries.
Reading shapefile: This allows us to get the shape of each state on the map.
Colour conversion and assignment: The colour assigned to each state by our graph colouring algorithm is mapped to an actual colour (e.g., 'r' for red) that can be visualized. Each state is then filled with the corresponding colour.
Visualization: The filled map is displayed using
plt.show
()
.
In summary, this code provides a solution to colour the U.S. map where neighbouring states have distinct colours. It employs a recursive backtracking approach to determine the colouring and uses the Basemap toolkit to visualize the results.