如何用 TikZ 绘制邻接数组?

如何用 TikZ 绘制邻接数组?

我将绘制一个图形表示为邻接数组,也是这样的:

例子

怎么做?我没有找到像上图这样的示例。

答案1

起点:

在此处输入图片描述

代码:

\documentclass[border=2pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix,positioning,arrows.meta,arrows}

\tikzset{
mymat/.style={
  matrix of math nodes,
  text height=2.5ex,
  text depth=0.75ex,
  text width=3.25ex,
  align=center,
  column sep=-\pgflinewidth
  },
mymats/.style={
  mymat,
  nodes={draw,fill=#1}
  }  
}
\begin{document}

\begin{tikzpicture}[>=latex]
\matrix[mymat,anchor=west,row 2/.style={nodes=draw}]
at (0,0) 
(mat1)
{
0 & 1 & 2 & 3 & 4 \\
2 & 1 & 3 & 2 & 1 \\
};
\matrix[mymat,right=of mat1,row 2/.style={nodes={draw,fill=gray!30}}]
(mat2)
{
5 & 6 & 7 & 8 \\
2 & 1 & 2 & 1 \\
};
\matrix[mymats=white,anchor=west]
at (0,-2) 
(mat3)
{
1 & 2 & 0 & 0 & 3 & ? & 2 & 4 & 3 \\
};
\matrix[mymats=gray!30,right=of mat3]
(mat4)
{
? & 6 & 7 & 5 & 8 & 7 & ? \\
};

\node[above=0pt of mat1]
  (cella) {Cell A};
\node[above=0pt of mat2]
  (cellb) {Cell B};
\node at (mat4-1-7.north|-cellb)
  (cellx) {Cell X};

\begin{scope}[shorten <= -2pt]
\draw[*->]
  (mat1-2-1.south) -- (mat3-1-1.north);
\draw[*->]
  (mat1-2-2.south) -- (mat3-1-3.north);
\draw[*->]
  (mat1-2-3.south) -- (mat3-1-4.north);
\draw[*->]
  (mat1-2-4.south) -- (mat3-1-7.north);
\draw[*->]
  (mat1-2-5.south) -- (mat3-1-9.north);

\draw[*->]
  (mat2-2-1.south) -- (mat4-1-1.north);
\draw[*->]
  (mat2-2-2.south) -- (mat4-1-3.north);
\draw[*->]
  (mat2-2-3.south) -- (mat4-1-4.north);
\draw[*->]
  (mat2-2-4.south) -- (mat4-1-6.north);

\draw[*->,dashed,line width=0.7pt]
  (mat4-1-1.north) to[out=90,in=-60,looseness=0.4] (mat1-2-3.south);
\draw[*->,dashed,line width=0.7pt]
  (mat3-1-6.north) to[out=90,in=-90] (mat2-2-1.south);
\draw[*->,dashed,line width=0.7pt]
  (mat4-1-7.north) ..
    controls ++ (0.5,0.5) and ++(-1,-0.7) ..  
  (cellx.south);
\end{scope}
\end{tikzpicture}

\end{document}

相关内容