Spanning-Tree Cost Calculation

Laz, based on the following screen shot, I did understand how “spanning-tree” works, however, I still did NOT understand how “SW3” selected the “D” port nor the “A” port. No issue with the “R” port.
Also I didn’t understand based on what “S5” selected the “A” port. Please help me out understand this piece of info. Your help is greatly appreciated. Thanks!
image