1.无向图使用邻接矩阵表示:(二维数组)
输入示例:
8
12
(0,1) (0,2) (0,5) (0,6) (0,7) (1,7) (2,7) (3,4) (3,5) (4,5) (4.6) (4,7)
package Matriix; import java.util.Scanner; public class Demo1 { //无向图的连接矩阵法 public static void main(String[] args) { Scanner scan = new Scanner(System.in); int V = scan.nextInt();//V表示顶点的个数 int E = scan.nextInt();//E表示边的条数 boolean adj[][] = new boolean[V][V]; for(int i=0;i<V;i++){ for(int j=0;j<V;j++){ adj[i][j] = false; } } for(int i=0;i<V;i++){ adj[i][i] = true; } for(int i=0;i<E;i++){//输入格式为(x,y) String input = scan.next(); int x = Integer.parseInt(input.substring(1, 2)); int y = Integer.parseInt(input.substring(3, 4)); adj[x][y] = true; adj[y][x] = true; } //打印 for(int i=0;i<V;i++){ for(int j=0;j<V;j++){ System.out.print(adj[i][j]+" "); } System.out.println(); } } }
输入示例:
8
12
(0,1) (0,2) (0,5) (0,6) (0,7) (1,7) (2,7) (3,4) (3,5) (4,5) (4.6) (4,7)
package Matriix; import java.util.Scanner; public class Demo2 { //无向图的邻接表 public static void main(String[] args) { Scanner scan = new Scanner(System.in); int V = scan.nextInt();//顶点的个数 int E = scan.nextInt();//边的条数 Node adj[] = new Node[V]; for(int i=0;i<V;i++){ adj[i] = null; } for(int i=0;i<E;i++){ String input = scan.next(); int x = Integer.parseInt(input.substring(1, 2)); int y = Integer.parseInt(input.substring(3, 4)); adj[y] = new Node(x,adj[y]); adj[x] = new Node(y,adj[x]); } for(int i=0;i<V;i++){ for(Node temp=adj[i];temp!=null;temp=temp.next){ System.out.print(temp.val+" "); } System.out.println(); } } static class Node{ int val; Node next; public Node(int val,Node next){ this.val = val; this.next = next; } } }