java中无向图的两种表示

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



  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值