Function Repository Resource:

QueensGraph

Source Notebook

Generate the queen's graph

Contributed by: Alejandra Ortiz Duran

ResourceFunction["QueensGraph"][n]

generates a undirected graph with n2 vertices representing chess board positions and edges indicating valid moves between configurations.

ResourceFunction["QueensGraph"][{m,n}]

generates a undirected graph with m×n vertices representing positions of a rectangular chess board.

Details

ResourceFunction["QueensGraph"] takes the same options as Graph.

Examples

Basic Examples (2) 

The first few n-queens graphs:

In[1]:=
Table[ResourceFunction["QueensGraph"][i, PlotLabel -> Subscript[S, i]], {i, 2, 4}]
Out[1]=

Some rectangular queens graphs:

In[2]:=
Table[ResourceFunction["QueensGraph"][{i, j}, PlotLabel -> Subscript[Q, i, j]], {i, 5, 6}, {j, 3, 4}]
Out[2]=

Scope (1) 

The n-Queens graph is automatically laid out in the order of the appearance of the square numbering on the chessboard:

In[3]:=
ResourceFunction["QueensGraph"][4, VertexSize -> Medium, VertexLabels -> Placed[Automatic, Center]]
Out[3]=

Options (6) 

GraphHighlight (2) 

Highlight vertex 1:

In[4]:=
HighlightGraph[
 ResourceFunction["QueensGraph"][6, VertexSize -> Medium], {1}]
Out[4]=

Highlight the edge 26:

In[5]:=
HighlightGraph[
 ResourceFunction["QueensGraph"][5, VertexSize -> Medium], 2 \[UndirectedEdge] 6]
Out[5]=

VertexLabels (2) 

Label individual vertices:

In[6]:=
ResourceFunction["QueensGraph"][4, VertexSize -> Large, VertexLabels -> {2 -> Placed["A", Center]}]
Out[6]=

Label all vertices:

In[7]:=
ResourceFunction["QueensGraph"][5, VertexSize -> Large, VertexLabels -> Placed[Automatic, Center]]
Out[7]=

VertexSize (2) 

By default, the size of vertices is computed automatically:

In[8]:=
ResourceFunction["QueensGraph"][4, VertexSize -> Automatic]
Out[8]=

Specify the size of all vertices using symbolic vertex size:

In[9]:=
Table[ResourceFunction["QueensGraph"][4, VertexSize -> s, PlotLabel -> s], {s, {Tiny, Small, Medium, Large}}]
Out[9]=

Applications (2) 

Visualize valid moves for the queen:

In[10]:=
HighlightGraph[ResourceFunction["QueensGraph"][{12, 10}], AdjacencyList[ResourceFunction["QueensGraph"][{12, 10}], 53], VertexStyle -> {53 -> Blue}, VertexSize -> {53 -> Medium}, VertexSize -> Medium]
Out[10]=

The vertex coloring of the queen's graph:

In[11]:=
g = ResourceFunction["QueensGraph"][8, VertexSize -> Large];
In[12]:=
Annotate[g, {VertexStyle -> Thread[VertexList[g] -> FindVertexColoring[g, ColorData[106, "ColorList"]]]}]
Out[12]=

Publisher

Wolfram Summer School

Version History

  • 1.0.0 – 21 June 2023

Related Resources

License Information