我想创建一个可视化的Bellman-Ford 算法。为此,我需要将权重(数字或 $\infty$)和前任(字母)的信息添加到每个节点中。这应该看起来像这样(使用 Gimp 完成):
我怎样才能用 LaTeX (Tikz) 来实现这个效果?
我目前正在创建我的图表:
\documentclass{beamer}
\usepackage{tikz}
\usepackage{verbatim}
\usetikzlibrary{arrows,shapes}
\begin{document}
\pgfdeclarelayer{background}
\pgfsetlayers{background,main}
\begin{frame}
\tikzstyle{vertex}=[circle,fill=black!25,minimum size=20pt,inner sep=0pt]
\begin{figure}
\begin{tikzpicture}[scale=2.5, auto,swap]
% First we draw the vertices
\foreach \pos/\name in {{(0,2)/a}, {(1,2)/b}, {(2,2)/c},
{(0,1)/d}, {(1,1)/e}, {(2,1)/f},
{(0,0)/g}, {(1,0)/h}, {(2,0)/i}}
\node[vertex] (\name) at \pos {$\name$};
% Connect vertices with edges and draw weights
\foreach \source/ \dest /\weight/\style in {a/b/0/, b/c/1/, a/d/2/, e/d/5/,
b/e/3/bend right, e/b/-1/bend right, b/f/4/above, f/i/3/,
i/e/1/, g/h/1/}
\path (\source) edge[->,\style, thick] node {$\weight$} (\dest);
\end{tikzpicture}
\end{figure}
\end{frame}
\end{document}
答案1
您可以使用 放置文本label={[<options>]center:<text>}
,其中 center 将标签放在“主机”节点的中间,因此您必须使用标签的xshift=..., yshift=...
来移动它。<options>
\documentclass{beamer}
\usepackage{tikz}
\usepackage{verbatim}
\usetikzlibrary{arrows,shapes}
\begin{document}
\pgfdeclarelayer{background}
\pgfsetlayers{background,main}
\begin{frame}
\tikzset{
vertex/.style={
circle,
fill=black!25,
minimum size=20pt,
inner sep=0pt,
text height=1ex,
text depth=1ex,
label={[weight label]center:\weight},
label={[pred label]center:\pred}
},
pred label/.style={
font=\tiny,
xshift=0.3em,
yshift=-0.8ex,
text height=1ex,
text depth=0pt
},
weight label/.style={
font=\tiny,
xshift=-0.3em,
yshift=-0.8ex,
text height=1ex,
text depth=0pt
}
}
\begin{figure}
\begin{tikzpicture}[scale=2.5, auto,swap]
% First we draw the vertices
\foreach \pos/\name/\weight/\pred in {%
{(0,2)/a/0/g},%
{(1,2)/b/$\infty$/a}%
}
\node[vertex] (\name) at \pos {$\name$};
% Connect vertices with edges and draw weights
\foreach \source/ \dest /\weight/\style in {a/b/0/}
\path (\source) edge[->,\style, thick] node {$\weight$} (\dest);
\end{tikzpicture}
\end{figure}
\end{frame}
\end{document}