答案1
您可以使用label
狀態以外的文字和節點來標記邊緣。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning,arrows.meta}
\tikzset{%
node distance=2cm,
State/.style={%
draw,circle,
thick,
color=black!60!green,
inner sep=0pt,
minimum size=10mm,
fill=blue!40!green,
text=white,
},
StateMark/.style={%
State,
fill=black},
Edge/.style={%
color=blue!40!green,
very thick,
-{Triangle[scale=1.1]},%% Try Latex instead oc Triangle
text=black,
},
EdgeMark/.style={%
Edge,
color=blue!90!green,
text=black,
}
}
\begin{document}
\begin{tikzpicture}
\node[StateMark,label=90:r] (S1) {$\infty$};
\node[StateMark,label=90:s,right=of S1] (S2){0};
\node[State,label=90:t,right=of S2] (S3){2};
\node[State,label=90:x,right=of S3] (S4){6};
%%
\draw[Edge] (S1) -- node[above,pos=0.5]{5} (S2);
\draw[Edge] (S1) to[bend right] node[below,pos=0.5]{5} (S3);%% Default bend = 30 degrees
\draw[EdgeMark] (S2) -- node[above,pos=0.5]{2} (S3);
\draw[EdgeMark] (S2) to[bend left=40] node[above,pos=0.5]{5} (S4);
\draw[Edge] (S3) -- node[above,pos=0.5]{7} (S4);
\end{tikzpicture}
\end{document}
為了簡化程式碼,可以State
透過將定義變更為將標籤文字作為輸入給出
State/.style={%
draw,circle,
thick,
color=black!60!green,
inner sep=0pt,
minimum size=10mm,
fill=blue!40!green,
text=white,
label=90:#1,
},
StateMark/.style={%
State=#1,
fill=black},
然後將狀態繪製為
\node[StateMark=r] (S1) {$\infty$};
\node[StateMark=s,right=of S1] (S2){0};
\node[State=t,right=of S2] (S3){2};
\node[State=x,right=of S3] (S4){6};