Java实现邻接表

package GraphBase;

import java.util.*;

public class ljtable {
     
	static int n, m; // 顶点数n,边数m
	static ArrayList<edge>[] G = new ArrayList[100005]; // 图G的邻接表

	static class edge {
     
		// 边的终点编号v,边权w
		int v, w;

		edge(int v, int w) {
     
			this.v = v;
			this.w = w;
		}
	}

	public static void function(int x) {
     
		// 遍历邻接表中,每个节点的相邻节点
		for (int i = 0; i < G[x].size(); i++) {
     
			int v = G[x].get(i).v;
			int w = G[x].get(i).w;
		}
	}

	public static void main(String[] args) {
     
		Scanner cin = new Scanner(System.in);
		n = cin.nextInt();
		//m = cin.nextInt();
		// 将G数组中的每一个ArrayList元素都要初始化
		for (int i = 0; i <= n; i++) {
     
			G[i] = new ArrayList<edge>();
		}
		// 加入新边,从v1到v2,权值为w
		/*
		 * for (int i = 0; i < n; i++) { int v1 = sc.nextInt(); int v2 = sc.nextInt();
		 * int w = sc.nextInt(); G[v1].add(new edge(v2, w)); // 如果是无向图 G[v2].add(new
		 * edge(v1, w)); }
		 */
		int g[][] = new int[101][101];
		int cnt = 0;
		int vis1 = 0;
		int vis2 = 0;
		for (int i = 1; i <= n; i++) {
     
			for (int j = 1; j <= n; j++) {
     
				g[i][j] = cin.nextInt();
			}
		}
		for(int i = 1;i <= n;i++)
			for(int j = 1;j <= n;j++){
     
				g[i][j]	 = Math.max(g[i][j], g[j][i]);
			}

		for(int i = 1;i <= n;i++) {
     
			for(int j = 1;j <= n;j++){
     
				if(j == 1)
				System.out.print(g[i][j]);
				else System.out.print(" " + g[j][i]);
			}
			System.out.println();
			}
		
	}
}

你可能感兴趣的:(Java,图论)