자료구조 & 알고리즘/그래프

그래프 구현 예시 코드 (인접 행렬 - 무방향 그래프)

꾸준함의 미더덕 2024. 1. 8. 19:47
class GraphMatrix {
    char[] vertices; // 노드
    int[][] matrix; // 인접 행렬
    int idx;

    public GraphMatrix(int size) {
        this.vertices = new char[size];
        this.matrix = new int[size][size];
        this.idx = 0;
    }
    
    public boolean isFull(){
        return this.vertices.length == idx;
    }

    public void addVertex(char c) {
        if(isFull()){
            System.out.println("Graph is full");
            return;
        }
        this.vertices[this.idx++] = c;
    }

    public void addEdge(int x, int y) { // 무방향 그래프 
        this.matrix[x][y] = 1; 
        this.matrix[y][x] = 1;
    }

    public void printAdjacentMatrix() {
        System.out.print("  ");
        for (int i = 0; i < this.vertices.length; i++) {
            System.out.print(vertices[i] + " ");
        }
        System.out.println();
        for (int i = 0; i < this.vertices.length; i++) {
            System.out.print(vertices[i] + " ");
            for (int j = 0; j < matrix.length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

public class Main {
    public static void main(String[] args) {
        // Test code
        GraphMatrix graph = new GraphMatrix(4);

        graph.addVertex('A');
        graph.addVertex('B');
        graph.addVertex('C');
        graph.addVertex('D');

        graph.addEdge(0, 1);
        graph.addEdge(0, 2);
        graph.addEdge(1, 2);
        graph.addEdge(1, 3);
        graph.addEdge(2, 3);
        graph.printAdjacentMatrix();
    }
}