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

2023. 12. 26. 23:50·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, 생능출판사)

'Data Structure > 자료구조' 카테고리의 다른 글

[자료구조] 스택의 응용 - 괄호 검사 문제  (0) 2024.01.15
[자료구조] 스택(Stack)  (0) 2023.12.31
[자료구조] 배열의 응용 : 다항식  (0) 2023.12.26
[자료구조] 순차리스트  (0) 2023.12.24
[자료구조] 배열을 이용한 리스트 구현  (0) 2023.12.24
'Data Structure/자료구조' 카테고리의 다른 글
  • [자료구조] 스택의 응용 - 괄호 검사 문제
  • [자료구조] 스택(Stack)
  • [자료구조] 배열의 응용 : 다항식
  • [자료구조] 순차리스트
lumana
lumana
배움을 나누는 공간 https://github.com/bebeis
  • lumana
    Brute force Study
    lumana
  • 전체
    오늘
    어제
    • 분류 전체보기
      • Spring
        • MVC
        • DB
        • 핵심 원리
        • JPA
      • WEB
        • HTML
        • CSS
        • HTTP
        • Application
      • Computer Science
        • Network
        • Database
        • OS
        • 시스템 프로그래밍
        • 컴퓨터구조
      • Algorithm
        • Divide&Conquer
        • Sort
        • Greedy
        • DP
        • Backtracking
        • NP-Complete
        • Graph
      • Data Structure
        • 자료구조
        • C++ STL
        • Java Collection
      • 소프트웨어 공학
        • 시험 공부 정리
        • Theorem
      • Programming Language
        • Python
        • Java
        • C
        • C++
        • Rust
        • Theory
      • Unix_Linux
        • Common
      • React
      • PS
        • BOJ
        • Tip
        • 프로그래머스
        • CodeForce
      • Book Review
        • Clean Code
      • Math
        • Linear Algebra
      • AI
        • DL
        • ML
        • DA
        • Concepts
      • 우아한테크코스
        • 프리코스
      • Project Review
      • LegacyPosts
      • Android
      • Apple
        • Mac
        • IPhone
        • IPad
      • 모니터
      • Diary
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

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

티스토리툴바