I think you'd do better to use an existing dependency graphing tool. For example: generating-dependency-graphs
Taking your example, and using Mermaid, the graph description looks like this:
graph TD
A -->P1
A -->P2
B -->P1
B -->P5
B -->B1
X -->P1
X -->J1
Y -->P5
S -->R1
S -->X
And the result looks like this: