Best way to convert a 2D array into a graph

I have a 2D array of M x N which has 1s and 0s. I should convert it into an undirected graph.

For example,
1 1 1
1 0 1
1 1 1
should output that the above-given graph has 8 vertices and 8 edges ([0,1], [1,2], [2,4], [4,7],[7,6],[6,5],[5,3],[3,0])

I don’t know if its the best but you can create a variable count=0 and iterate over the matrix and replace every ‘1’ with ++count.
So now your array would look like this :

1 2 3
4 0 5
6 7 8

(You have ‘count’ number of nodes)
Now again iterate and for each non-zero value you encounter, check all its adjacent values and correspondingly update the adjacency matrix or list.