java中无向图的两种表示

来源:互联网 发布:mac 端口号被占用 编辑:程序博客网 时间:2024/06/05 09:45

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;}}}



0 0
原创粉丝点击