Interview Question
Country: United States
Here's the rough idea with half-working code in Python. The idea is simple and mainly involved serializing and deserializing.
import json
import psycopg2
jsonData = '''
{
"data": [
{
"source": "A",
"target": "B",
"distance": 6
},
{
"source": "A",
"target": "E",
"distance": 4
},
{
"source": "B",
"target": "A",
"distance": 6
},
{
"source": "B",
"target": "C",
"distance": 2
},
{
"source": "B",
"target": "D",
"distance": 4
},
{
"source": "C",
"target": "B",
"distance": 3
},
{
"source": "C",
"target": "D",
"distance": 1
}
]
}
'''
# Serialize the data
serializedData = json.dumps(jsonData)
# Connect to the database
conn = psycopg2.connect(database=db, user=user, password=password, host=host, port=port)
cursor = conn.cursor()
# Insert the data
cursor.execute('INSERT INTO GRAPH VALUES %s' % (serializedData))
conn.commit()
conn.close()
# Deserialize the data to find shortest path
graphData = json.loads(serializedData)
graph = buildGraph(graphData)
sourceVertex = 'A'
print(dijkstra(graph, sourceVertex))
Form the adjacency matrix from the data sent , and then run the bfs/dfs on the matrix.
- Arjuna August 06, 2018How to create a matrix, is the question here. Since the data sent can be of variable length.