[자료구조] 배열의 응용 : 희소행렬

2023. 12. 26. 23:50·Computer Science/Data Structure

배열의 응용 : 희소행렬


  • 행렬을 표현하는 첫 번째 방법 : 2차원 배열을 사용

    #define MAX_ROWS 100
    #define MAX_COLS 100
    int matrix[MAX_ROWS][MAX_COLS];
    • 단점 : 많은 항들이 0으로 되어 있는 희소행렬의 경우메모리의 낭비가 심하게 됨

    • 첫 번째 방법을 통해 전치행렬 구하기

    #include <stdio.h>
    #define ROWS 3
    #define COLS 3
    // 행렬 전치 함수
    void matrix_transpose(int A[ROWS][COLS], int B[ROWS][COLS])
    {
        for (int r = 0; r<ROWS; r++)
            for (int c = 0; c<COLS; c++)
                B[c][r] = A[r][c];
    }
    void matrix_print(int A[ROWS][COLS])
    {
        printf("====================\n");
        for (int r = 0; r<ROWS; r++) {
            for (int c = 0; c<COLS; c++)
                printf("%d ", A[r][c]);
            printf("\n");
        }
        printf("====================\n");
    }
    
    int main(void)
    {
        int array1[ROWS][COLS] = { { 2,3,0 },
                    { 8,9,1 },
                    { 7,0,5 } };
        int array2[ROWS][COLS];
    
        matrix_transpose(array1, array2);
        matrix_print(array1);
        matrix_print(array2);
        return 0;
    }
  • 행렬을 표현하는 두 번째 방법 : 0이 아닌 요소들만 나타낸다

    • 0이 아닌 노드만을 (행, 열, 값)으로 표시
    typedef struct {
        int row;
        int col;
        int value;
    } element;
    
    typedef struct SparseMatrix {
        element data[MAX_TERMS];
        int rows; // 행의 개수
        int cols; // 열의 개수
        int terms; // 항의 개수
    }
    • 두 번째 방법을 통해 전치행렬 구하기
    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAX_TERMS 100
    typedef struct {
        int row;
        int col;
        int value;
    } element;
    
    typedef struct SparseMatrix {
        element data[MAX_TERMS];
        int rows;    // 행의 개수
        int cols;    // 열의 개수
        int terms;     // 항의 개수
    } SparseMatrix;
    
    SparseMatrix matrix_transpose2(SparseMatrix a)
    {
        SparseMatrix b;
    
        int bindex;        // 행렬 b에서 현재 저장 위치
        b.rows = a.rows;
        b.cols = a.cols;
        b.terms = a.terms;
    
        if (a.terms > 0) {
            bindex = 0;
            for (int c = 0; c < a.cols; c++) {
                for (int i = 0; i < a.terms; i++) {
                    if (a.data[i].col == c) {
                        b.data[bindex].row = a.data[i].col;
                        b.data[bindex].col = a.data[i].row;
                        b.data[bindex].value = a.data[i].value;
                        bindex++;
                    }
                }
            }
        }
        return b;
    }
    
    void matrix_print(SparseMatrix a)
    {
        printf("====================\n");
        for (int i = 0; i<a.terms; i++) {
            printf("(%d, %d, %d) \n", a.data[i].row, a.data[i].col, a.data[i].value);
        }
        printf("====================\n");
    }
    
    int main(void)
    {
        SparseMatrix m = {
            { { 0, 3, 7 },{ 1, 0, 9 },{ 1, 5, 8 },{ 3, 0, 6 },{ 3, 1, 5 },{ 4, 5, 1 },{ 5, 2, 2 } },
            6,
            6,
            7
        };
        SparseMatrix result;
    
        result = matrix_transpose2(m);
        matrix_print(result);
        return 0;
    }

참조) C언어로 쉽게 풀어 쓴 자료구조(천인국, 2016, 생능출판사)

'Computer Science > Data Structure' 카테고리의 다른 글

[자료구조] 스택의 응용 - 괄호 검사 문제  (0) 2024.01.15
[자료구조] 스택(Stack)  (0) 2023.12.31
[자료구조] 배열의 응용 : 다항식  (0) 2023.12.26
[자료구조] 순차리스트  (0) 2023.12.24
[자료구조] 배열을 이용한 리스트 구현  (0) 2023.12.24
'Computer Science/Data Structure' 카테고리의 다른 글
  • [자료구조] 스택의 응용 - 괄호 검사 문제
  • [자료구조] 스택(Stack)
  • [자료구조] 배열의 응용 : 다항식
  • [자료구조] 순차리스트
lumana
lumana
배움을 나누는 공간 https://github.com/bebeis
  • lumana
    Brute force Study
    lumana
  • 전체
    오늘
    어제
    • 분류 전체보기 (456)
      • Software Development (27)
        • Performance (0)
        • TroubleShooting (1)
        • Refactoring (0)
        • Test (8)
        • Code Style, Convetion (0)
        • DDD (0)
        • Software Engineering (18)
      • Java (71)
        • Basic (5)
        • Core (21)
        • Collection (7)
        • 멀티스레드&동시성 (13)
        • IO, Network (8)
        • Reflection, Annotation (3)
        • Modern Java(8~) (12)
        • JVM (2)
      • Spring (53)
        • Framework (12)
        • MVC (23)
        • Transaction (3)
        • AOP (11)
        • Boot (0)
        • AI (0)
      • DB Access (1)
        • Jdbc (1)
        • JdbcTemplate (0)
        • JPA (14)
        • Spring Data JPA (0)
        • QueryDSL (0)
      • Computer Science (129)
        • Data Structure (27)
        • OS (14)
        • Database (10)
        • Network (21)
        • 컴퓨터구조 (5)
        • 시스템 프로그래밍 (23)
        • Algorithm (29)
      • HTTP (8)
      • Infra (1)
        • Docker (1)
      • 프로그래밍언어론 (15)
      • Programming Language(Sub) (77)
        • Kotlin (1)
        • Python (25)
        • C++ (51)
        • JavaScript (0)
      • FE (11)
        • HTML (1)
        • CSS (9)
        • React (0)
        • Application (1)
      • Unix_Linux (0)
        • Common (0)
      • PS (13)
        • BOJ (7)
        • Tip (3)
        • 프로그래머스 (0)
        • CodeForce (0)
      • Book Review (4)
        • Clean Code (4)
      • Math (3)
        • Linear Algebra (3)
      • AI (7)
        • DL (0)
        • ML (0)
        • DA (0)
        • Concepts (7)
      • 프리코스 (4)
      • Project Review (6)
      • LegacyPosts (11)
      • 모니터 (0)
      • Diary (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
lumana
[자료구조] 배열의 응용 : 희소행렬
상단으로

티스토리툴바