We'll print the list of edges "on the fly" by processing the adjacency matrix sequentially: row by row from top to bottom, and within each row from left to right. For each entry equal to in the adjacency matrix, print the pair of vertices that defines the corresponding edge. With this traversal, the vertex pairs are automatically ordered by the first vertex.
Example
The graph shown in the example has the following form:
Algorithm implementation
Read the adjacency matrix of the graph. Since the graph is undirected, print only those edges for which i < j.
scanf("%d",&n);
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
{
scanf("%d",&val);
if (i < j && val == 1)
printf("%d %d\n",i,j);
}Java implementation
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int n = con.nextInt();
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
{
int val = con.nextInt();
if (i < j && val == 1)
System.out.println(i + " " + j);
}
con.close();
}
}