A graph is a set of nodes and edges that connect those nodes.
There are two types of graphs; directed and undirected. In an undirected graph, the edges between nodes have no particular direction (like a two-way street) whereas in a directed graph, each edge has a direction associated with it (like a one-way street).
0 --- 1 --- 3
\ /
\ /
2
For two nodes in a graph to be considered adjacent to one another, there must be an edge between them. In the example given above, nodes 0 and 1 are adjacent, but nodes 0 and 2 are not.
We can encode graphs using an adjaceny matrix. An adjacency matrix for a graph with n nodes is an n x n matrix where the entry at row i and column j is a 0 if nodes i and j are not adjacent, and 1 if nodes i and j are adjacent.
For the example above, the adjacency matrix would be as follows:
# 0 1 2 3 Node edge goes to
[
[ 0, 1, 0, 0 ], # Node 0
[ 1, 0, 1, 1 ], # Node 1
[ 0, 1, 0, 1 ], # Node 2
[ 0, 1, 1, 0 ] # Node 3
]A one indicates that a connection is True and a zero indicates a connection is False.
Here is how the above model might be written out:
- On the first row, node
0does not connect to itself, but it does connect to node1. It does not connect to node2or node3. The row is written as0, 1, 0, 0. - On the second row, node
1connects to node0, node2and node3, but it does not connect to itself. The row is written as1, 0, 1, 1. - On the third row, node
2does not connect to node0, but it does connect to node1, does not connect to itself, and it does connect to node3. The row is written as0, 1, 0, 1. - On the fourth row, node
3does not connect to node0, but it does connect to node1and node2. It does not connect to itself. The row is written as0, 1, 1, 0.
Your task is to write a function which determines if two nodes are adjacent in a graph when given the adjacency matrix and the two nodes.
Adjacency Matrix (for matrix above):
[
[ 0, 1, 0, 0 ],
[ 1, 0, 1, 1 ],
[ 0, 1, 0, 1 ],
[ 0, 1, 1, 0 ]
]- Nodes
0,1should returnTrue. - Nodes
0,2should returnFalse.
0 --- 1
/ | |
4 | |
\ | |
3 --- 2
[
[ 0, 1, 0, 1, 1 ], # Node 0
[ 1, 0, 1, 0, 0 ], # Node 1
[ 0, 1, 0, 1, 0 ], # Node 2
[ 1, 0, 1, 0, 1 ], # Node 3
[ 1, 0, 0, 1, 0 ] # Node 4
]- Nodes
0,3should returnTrue. - Nodes
1,4should returnFalse.
- Checkout the challenge on Edabit to see the graphs more clearly ;)