C#

무방향 그래프의 인접행렬 2차원 배열로 구현하기

s0002 2023. 1. 29. 18:04

google 검색 이미지

using System;
using System.Collections.Generic;
namespace UndirectedGraph
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());

            string[] citys = new string[n];
            citys = Console.ReadLine().Split(' ');

            //1 서울, 2 대구, 3 대전, 4 부산
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(0, null);
            int key = 1;

            foreach(var c in citys)
            {
                dic.Add(key, c);
                key++;
            }
            
            int[,] adjacencyMatrix = new int[n + 1, n + 1];
            int[] io = new int[2];

            //반복 횟수<=n*n
            for (int i=0; i<n*n;i++)
            {
                string input = Console.ReadLine();

                //1을 넣지 않는 곳도 있을 수 있으므로 반복 종료 조건 필요
                if (input == " ") 
                    break;

                io = Array.ConvertAll(input.Split(' '), int.Parse);
                adjacencyMatrix[io[0], io[1]] = 1;
                //무방향 그래프이므로 대각선 아래쪽도 1 넣어줘야 함
                adjacencyMatrix[io[1], io[0]] = 1;
            }
            
            for(int i = 0; i < n + 1; i++)
            {
                for (int j = 0; j< n + 1; j++)
                {
                    Console.Write(adjacencyMatrix[i, j]);
                }
                Console.WriteLine();
            }      
        }
    }
}

'C#' 카테고리의 다른 글

재귀함수(Recursive call)  (0) 2023.02.07
오브젝트 풀링(Object Pool)  (1) 2023.02.05
이분탐색/이진탐색/Binary Search  (0) 2023.01.29
미션, 아이템 엑셀->json->데이터  (0) 2023.01.13
리스트, 스택, 큐 직렬화/역직렬화  (0) 2023.01.13