Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class GraphAdjacentMatrix {
- private boolean adjMatrix[][];
- private int numVertices;
- public GraphAdjacentMatrix(int numVertices) {
- this.numVertices = numVertices;
- adjMatrix = new boolean[numVertices][numVertices];
- }
- public void setEdge(int i, int j) {
- adjMatrix[i][j] = true;
- adjMatrix[j][i] = true;
- }
- public void delEdge(int i, int j) {
- adjMatrix[i][j] = false;
- adjMatrix[j][i] = false;
- }
- public boolean isEdge(int i, int j) {
- return adjMatrix[i][j];
- }
- public int first(int v1){
- boolean[] ary = this.adjMatrix[v1];
- int firstNeighborIndex = this.numVertices; // return n if none
- for (int i = 0; i < ary.length; i++) {
- if (ary[i] != false){
- firstNeighborIndex = i;
- break;
- }
- }
- return firstNeighborIndex;
- }
- public int next(int v1, int v2){
- boolean[] ary = this.adjMatrix[v1];
- int nextNeighborIndex = this.numVertices; // return n if none
- for (int i = v2 + 1; i < ary.length; i++) {
- if (ary[i] != false){
- nextNeighborIndex = i;
- break;
- }
- }
- return nextNeighborIndex;
- }
- public String toString() {
- StringBuilder s = new StringBuilder();
- for (int i = 0; i < numVertices; i++) {
- s.append(i + ": ");
- for (boolean j : adjMatrix[i]) {
- s.append((j?1:0) + " ");
- }
- s.append("\n");
- }
- return s.toString();
- }
- public static void main(String[] args) {
- GraphAdjacentMatrix gam = new GraphAdjacentMatrix(5);
- boolean isEdge;
- gam.setEdge(0, 1);
- isEdge = gam.isEdge(0, 1);
- gam.delEdge(0, 1);
- isEdge = gam.isEdge(0, 1);
- gam.setEdge(0, 1);
- gam.setEdge(0, 2);
- gam.setEdge(0, 4);
- int nextNeighbor;
- nextNeighbor = gam.first(0);
- nextNeighbor = gam.next(0, nextNeighbor);
- nextNeighbor = gam.next(0, nextNeighbor);
- nextNeighbor = gam.next(0, nextNeighbor);
- System.out.print(gam.toString());
- System.out.println();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement