GridGraph with diagonal edges

Mathematica has a built-in function :)

GraphData[{"King", {m, n}}]

GraphData[{"King", {3, 7}}]

enter image description here


n = {3, 5};
g = GridGraph[{n, n}, VertexLabels -> "Name"];
edAdd = Sort /@ UndirectedEdge @@@ Position[Outer[EuclideanDistance@## &, #, #, 1], 
                                            N@Sqrt@2] &@ GraphEmbedding@g // Union
EdgeAdd[g, edAdd]

Mathematica graphics


Clear[diagGraph]
diagGraph[n_Integer] :=
 EdgeAdd[
   GridGraph[{n, n}, VertexLabels -> "Name"],
   Join[
    Table[i <-> i + n + 1, {i, Select[Range[1, n^2 - n], Mod[#, n] != 0 &]}],
    Table[i <-> i + n - 1, {i, Select[Range[2, n^2 - n + 1], Mod[#, n] != 1 &]}]
   ]
 ]

diagGraph[5]

Mathematica graphics