I am trying to write a code in Ruby to convert a given graph's adjacency matrix to adjacency list. When I verified my solution for the given input mentioned here my output was slightly different. I need some direction in understanding where exactly is the issue. Below is my code:
def convert_adj_matrix_to_list(arr)
list = {}
start = 0
last = 0
arr.each_index do |row|
# row = [0, 0, 1]
puts "row = #{arr[row]}"
for col in 0..arr[row].size-1
puts "row = #{row}, col = #{col}"
puts "arr[#{row}][#{col}] = #{arr[row][col]}"
list[row] = col if arr[row][col] == 1
end
puts
end
list
end
arr = [ [0, 0, 1], [0, 0, 1], [1, 1, 0] ]
puts convert_adj_matrix_to_list(arr)
Output:
row = [0, 0, 1]
row = 0, col = 0
arr[0][0] = 0
row = 0, col = 1
arr[0][1] = 0
row = 0, col = 2
arr[0][2] = 1
row = [0, 0, 1]
row = 1, col = 0
arr[1][0] = 0
row = 1, col = 1
arr[1][1] = 0
row = 1, col = 2
arr[1][2] = 1
row = [1, 1, 0]
row = 2, col = 0
arr[2][0] = 1
row = 2, col = 1
arr[2][1] = 1
row = 2, col = 2
arr[2][2] = 0
{0=>2, 1=>2, 2=>1}