Java二维数组存储无向图边时如何判断对称重复边避免重复添加
问题描述
需要为无向图实现边重复判定逻辑:若二维邻接矩阵中已存在[1][0]对应的边记录,后续输入反向边[0][1]时需判定为重复内容,不再执行添加操作。
问题分析
当前代码存在几个核心问题导致重复边无法被拦截:
- 边添加逻辑无前置校验:
addEdge、addEdge1方法只要接收到参数就直接写入邻接矩阵和邻接表,没有判断边是否已经存在 - 无向图的边是无方向的,
(u,v)和(v,u)属于同一条边,邻接矩阵中这两个位置的值会同步更新,判断任意一个位置的状态即可确认边是否存在 - 原有顶点越界校验分支缺少
continue,即使输入顶点序号不合法,仍会继续执行边添加逻辑 - 原有越界校验仅判断了顶点序号大于上限的场景,未覆盖负数索引的异常情况
修复方案
- 改造
addEdge方法,新增边存在性判断,返回布尔值标识本次是否真正完成了边添加 - 只有在邻接矩阵边添加成功时,才执行邻接表的边写入操作,避免邻接表出现重复记录
- 补全越界校验分支的流程控制,拦截非法输入后直接进入下一轮输入循环
- 检测到重复边时给出明确提示,回退循环计数让用户重新输入合法边
修改后完整代码
import java.util.Scanner; import java.util.ArrayList; import java.util.List; import java.util.Stack; public class MatrixGraph{ List<List<Integer>> graph; Scanner input = new Scanner(System.in); ArrayList<Connection> Links = new ArrayList<Connection>(); boolean visited[]; int nodes; int vertices; int matrix[][]; class Node { String name; boolean visited; ArrayList<Node> neighbors = new ArrayList<Node>(); Node(String name) { this.name = name; visited = false; } } class Connection { double fare; Node source, destination; Connection(Node source, Node destination) { this.source = source; this.destination = destination; } } public static void main(String[] args){ Scanner s = new Scanner(System.in); System.out.println("Enter the number of vertices"); int V = s.nextInt(); MatrixGraph amg = new MatrixGraph(V); int n1 = V-1; int n2 = V*n1; int maxSize = n2/2; while (true){ System.out.println("Enter the number of edges"); int E = s.nextInt(); if (E > maxSize){ System.out.println("Too Much Edges!"); continue; }else{ System.out.print("\n"); for(int i=0;i<E;i++){ System.out.print("Source: "); int mark = s.nextInt(); System.out.print("Destination: "); int mac = s.nextInt(); if (mark == mac) { System.out.println("\nERROR TRAPPED!!\nNo Loops Allowed Here!\nAdd New Edge!"); i--; continue; } else if(mark > (V-1)||mac > (V-1) || mark <0 || mac <0) { i--; System.out.println("\nInvalid vertex index!\n"); continue; } // 先尝试添加邻接矩阵边,判断是否重复 boolean addSuccess = amg.addEdge(mark,mac); if (!addSuccess) { System.out.println("\nEdge already exists! Please add a new edge.\n"); i--; continue; } // 邻接矩阵添加成功再更新邻接表 amg.addEdge1(mark,mac); } } } } MatrixGraph(int vertices){ graph = new ArrayList<>(); visited = new boolean[vertices]; this.vertices=vertices; matrix=new int[vertices][vertices]; for (int i = 0; i < vertices; i++){ graph.add(i, new ArrayList<>()); } } public boolean addEdge(int source,int destination){ // 无向图两个位置值同步,判断任意位置即可确认边是否存在 if (matrix[source][destination] == 1) { return false; } matrix[source][destination]= 1; matrix[destination][source]= 1; return true; } public void addEdge1(int a, int b) { graph.get(a).add(b); graph.get(b).add(a); } }
内容的提问来源于stack exchange,提问作者Mr. Ghost
相关产品推荐
相关产品推荐

