Swift Coding Test Course, Representation of Graphs

1. Introduction

Understanding algorithms and data structures is crucial in the field of software development. One of the problems that frequently appears in coding tests is related to graphs. A graph is a data structure composed of nodes (vertices) and edges, allowing data to be represented in various forms. In this course, we will deepen our understanding through algorithm problems related to graph representation.

2. Graph Representation

There are mainly two ways to represent a graph.

  • Adjacency Matrix: A two-dimensional array is used to represent the presence or absence of edges for all vertices in the graph. This method is useful when the number of vertices is small. The size of the array is O(V^2).
  • Adjacency List: This method stores the connected vertices as a list for each vertex. It is memory efficient and suitable for graphs with fewer edges. The time complexity of this method is O(V + E).

3. Problem Description

We will apply the graph representation methods through the following problem.

Problem: Friend Network

You are managing a network of N friends. Friend relationships are bidirectional, meaning if two friends are directly connected, they are friends with each other. Represent the friend relationship as a graph and write a program to check if two specific friends belong to the same friend group. A friend group includes all friends that are indirectly connected.

Input Format:

N (number of friends)
M (number of friend relationships)
For M lines, two friends A and B (1 ≤ A, B ≤ N) are given.
            

Output Format:

Print "YES" if A and B are in the same friend group, otherwise print "NO".
            

4. Problem Solving Process

4.1. Graph Creation

First, we need to create a graph based on the given friend relationships. We will implement this using an adjacency list. Here is a simple Swift code for graph creation.


import Foundation

// Adjacency list for graph representation
var graph: [Int: [Int]] = [:]

// Function to add friend relations
func addFriendRelation(friendA: Int, friendB: Int) {
    graph[friendA, default: []].append(friendB)
    graph[friendB, default: []].append(friendA)
}

// Function to create graph
func createGraph(N: Int, relations: [(Int, Int)]) {
    for (A, B) in relations {
        addFriendRelation(friendA: A, friendB: B)
    }
}
            

The above code creates a dictionary where each friend is a key and the value is the list of connected friends.

4.2. Finding Friend Groups

Now we can use one of the graph traversal algorithms to check if two friends belong to the same group. We can use Depth-First Search (DFS) or Breadth-First Search (BFS), and we will choose DFS here. DFS allows us to explore all related friends.


func dfs(start: Int, visited: inout Set<int>) {
    visited.insert(start)
    for friend in graph[start, default: []] {
        if !visited.contains(friend) {
            dfs(start: friend, visited: &amp;visited)
        }
    }
}

// Function to check if two friends are in the same group
func areInSameGroup(friendA: Int, friendB: Int) -&gt; Bool {
    var visited = Set<int>()
    dfs(start: friendA, visited: &amp;visited)
    return visited.contains(friendB)
}
            </int></int>

4.3. Entire Process

Now let’s integrate the entire process to solve the problem. Here is the code to read input, create the graph, and check the relationship of two friends.


let N = Int(readLine()!)! // Number of friends
let M = Int(readLine()!)! // Number of friend relationships

var relations = [(Int, Int)]()

for _ in 0..<m {="" let="" line="readLine()!.split(separator:" "="" ").map="" int($0)!="" }="" relations.append((line[0],="" line[1]))="" creategraph(n:="" n,="" relations:="" relations)="" checkline="readLine()!.split(separator:" if="" areinsamegroup(frienda:="" checkline[0],="" friendb:="" checkline[1])="" print("yes")="" else="" print("no")="" <="" code=""></m>
<p>The above code implements the logic to represent and verify friend relationships through the overall flow.</p>
<section> <h2>5. Conclusion</h2> <p>In this course, we explored how to represent graphs and how to use basic DFS algorithms to solve problems. Graphs are useful data structures that can be applied to various problems, and it is essential to become familiar with them through sufficient practice. Since such problems often appear in coding tests, I encourage you to improve your skills by solving problems multiple times.</p> </section> <footer> <p>© 2023 Swift Coding Test Course. All Rights Reserved.</p> </footer>
<p></p> <div id="jp-relatedposts" class="jp-relatedposts"> <h3 class="jp-relatedposts-headline"><em>관련</em></h3> </div>
<footer class="entry-footer"> <span class="byline"><span class="author vcard"><img alt="" src="https://secure.gravatar.com/avatar/5b7f47db621d1eab02540d35048be506?s=49&amp;d=mm&amp;r=g" srcset="https://secure.gravatar.com/avatar/5b7f47db621d1eab02540d35048be506?s=98&amp;d=mm&amp;r=g 2x" class="avatar avatar-49 photo" height="49" width="49" decoding="async"><span class="screen-reader-text">Author </span> <a class="url fn n" href="https://atmokpo.com/w/en/author/root/">root</a></span></span><span class="posted-on"><span class="screen-reader-text">Posted on </span><a href="https://atmokpo.com/w/34690/" rel="bookmark"><time class="entry-date published" datetime="2024-11-01T09:30:55+00:00">2024/11/01</time><time class="updated" datetime="2024-11-01T11:26:57+00:00">2024/11/01</time></a></span><span class="cat-links"><span class="screen-reader-text">Categories </span><a href="https://atmokpo.com/w/category/swift-coding-test/" rel="category tag">Swift Coding Test</a></span> </footer><!-- .entry-footer -->
<nav class="navigation post-navigation" aria-label="Posts"> <h2 class="screen-reader-text">Post navigation</h2> <div class="nav-links"><div class="nav-previous"><a href="https://atmokpo.com/w/34688/" rel="prev"><span class="meta-nav" aria-hidden="true">Previous</span> <span class="screen-reader-text">Previous post:</span> <span class="post-title">Swift Coding Test Course, Finding the Sum of Intervals 3</span></a></div><div class="nav-next"><a href="https://atmokpo.com/w/34694/" rel="next"><span class="meta-nav" aria-hidden="true">Next</span> <span class="screen-reader-text">Next post:</span> <span class="post-title">Swift Coding Test Course, Radix Sort</span></a></div></div> </nav>
<aside id="secondary" class="sidebar widget-area"> <section id="block-2" class="widget widget_block widget_search"><form role="search" method="get" action="https://atmokpo.com/w/en/" class="wp-block-search__button-outside wp-block-search__text-button wp-block-search"><label class="wp-block-search__label" for="wp-block-search__input-1">Search</label><div class="wp-block-search__inside-wrapper "><input class="wp-block-search__input" id="wp-block-search__input-1" placeholder="" value="" type="search" name="s" required=""><button aria-label="Search" class="wp-block-search__button wp-element-button" type="submit">Search</button></div></form></section><section id="block-10" class="widget widget_block"><ul class="wp-block-page-list"><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/c-coding-test-tutorials/">C++ Coding Test Tutorials</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/collection-of-c-coding-test-tutorials/">Collection of C# Coding Test Tutorials</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/deep-learning-automated-trading/">Deep learning Automated trading</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/deep-learning-natural-language-processing/">Deep learning natural language processing</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/english-sentence-study/">English sentence study</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/flutter-course/">Flutter course</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/gan-deep-learning-course/">GAN deep learning course</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/java-android-app-development/">Java Android app development</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/java-coding-test/">Java Coding Test</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/javascript-coding-test/">Javascript Coding Test</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/kotlin-android-app-development/">Kotlin Android app development</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/kotlin-coding-test/">Kotlin coding test</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/python-auto-trading/">Python Auto Trading</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/python-coding-test/">Python Coding Test</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/python-study/">Python Study</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/pytorch-study/">PyTorch Study</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/react-basics-course/">React basics course</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/spring-boot-backend-development/">Spring Boot backend development</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/swift-coding-test/">Swift Coding Test</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/swift-iphone-app-development-swiftui/">Swift iPhone app development (SwiftUI)</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/swift-iphone-app-development-uikit/">Swift iPhone app development (UIKit)</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/unity-basic/">Unity Basic</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/using-hugging-face/">Using Hugging Face</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/uwp-programming/">UWP Programming</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/wpf-programming/">WPF Programming</a></li></ul></section><section id="listcategorypostswidget-3" class="widget widget_listcategorypostswidget"><h2 class="widget-title">Category Post List</h2><ul class="lcp_catlist" id="lcp_instance_listcategorypostswidget-3"><li><a href="https://atmokpo.com/w/34716/">Swift Coding Test Course, Exploring Debugging Use Cases</a></li><li><a href="https://atmokpo.com/w/34714/">Swift Coding Test Course, Finding the Minimum Number of Coins</a></li><li><a href="https://atmokpo.com/w/34712/">Swift Coding Test Course, Exploring Dynamic Programming</a></li><li><a href="https://atmokpo.com/w/34710/">Swift Coding Test Course, Dijkstra</a></li><li><a href="https://atmokpo.com/w/34708/">Swift Coding Test Course, Bridge Building</a></li><li><a href="https://atmokpo.com/w/34706/">Swift Coding Test Course, Calculating the Area of a Polygon</a></li><li><a href="https://atmokpo.com/w/34704/">Swift Coding Test Course, Breadth-First Search</a></li><li><a href="https://atmokpo.com/w/34702/">Swift Coding Test Course, Sorting Digits in Descending Order</a></li><li><a href="https://atmokpo.com/w/34700/">Swift Coding Test Course, Calculate the Sum of Remainders</a></li><li><a href="https://atmokpo.com/w/34698/">Swift Coding Test Course, Depth First Search</a></li></ul><ul class="lcp_paginator"><li><a href="https://atmokpo.com/w/34690/?lcp_pagelistcategorypostswidget-3=10#lcp_instance_listcategorypostswidget-3" title="10" class="lcp_prevlink">&lt;&lt;</a></li><li><a href="https://atmokpo.com/w/34690/?lcp_pagelistcategorypostswidget-3=1#lcp_instance_listcategorypostswidget-3" title="1">1</a></li><span class="lcp_elipsis">...</span><li><a href="https://atmokpo.com/w/34690/?lcp_pagelistcategorypostswidget-3=6#lcp_instance_listcategorypostswidget-3" title="6">6</a></li><li><a href="https://atmokpo.com/w/34690/?lcp_pagelistcategorypostswidget-3=7#lcp_instance_listcategorypostswidget-3" title="7">7</a></li><li><a href="https://atmokpo.com/w/34690/?lcp_pagelistcategorypostswidget-3=8#lcp_instance_listcategorypostswidget-3" title="8">8</a></li><li><a href="https://atmokpo.com/w/34690/?lcp_pagelistcategorypostswidget-3=9#lcp_instance_listcategorypostswidget-3" title="9">9</a></li><li><a href="https://atmokpo.com/w/34690/?lcp_pagelistcategorypostswidget-3=10#lcp_instance_listcategorypostswidget-3" title="10">10</a></li><li class="lcp_currentpage">11</li><li><a href="https://atmokpo.com/w/34690/?lcp_pagelistcategorypostswidget-3=12#lcp_instance_listcategorypostswidget-3" title="12">12</a></li><li><a href="https://atmokpo.com/w/34690/?lcp_pagelistcategorypostswidget-3=13#lcp_instance_listcategorypostswidget-3" title="13">13</a></li><li><a href="https://atmokpo.com/w/34690/?lcp_pagelistcategorypostswidget-3=14#lcp_instance_listcategorypostswidget-3" title="14">14</a></li><li><a href="https://atmokpo.com/w/34690/?lcp_pagelistcategorypostswidget-3=12#lcp_instance_listcategorypostswidget-3" title="12" class="lcp_nextlink">&gt;&gt;</a></li></ul></section><section id="block-3" class="widget widget_block"> <div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow"> <h3 class="wp-block-heading">최신 글</h3> <ul class="wp-block-latest-posts__list wp-block-latest-posts"><li><a class="wp-block-latest-posts__post-title" href="https://atmokpo.com/w/37979/">Unity 2D Game Development, Create a Platform Game Including Jumps, Obstacles, and Enemies.</a></li> <li><a class="wp-block-latest-posts__post-title" href="https://atmokpo.com/w/37977/">Unity 2D Game Development, Adding Effects Using Particle System Implementing visual effects such as explosions and flames using the particle system.</a></li> <li><a class="wp-block-latest-posts__post-title" href="https://atmokpo.com/w/37973/">Unity 2D Game Development, Touch Input and Mobile Game Development Creation of 2D games utilizing touch input on mobile devices.</a></li> <li><a class="wp-block-latest-posts__post-title" href="https://atmokpo.com/w/37975/">Unity 2D Game Development, Power-Up and Buff System Creating a power-up system that temporarily enhances the player’s abilities.</a></li> <li><a class="wp-block-latest-posts__post-title" href="https://atmokpo.com/w/37971/">Unity 2D Game Development, Quest and Mission System Creating a quest system where rewards are given for achieving specific goals.</a></li> </ul></div></div> </section> </aside><!-- .sidebar .widget-area -->
<footer id="colophon" class="site-footer"> <div class="site-info"> <span class="site-title"><a href="https://atmokpo.com/w/en/" rel="home">라이브스마트</a></span> <a href="https://wordpress.org/" class="imprint"> Proudly powered by WordPress </a> </div><!-- .site-info --> </footer><!-- .site-footer -->
<link rel="stylesheet" id="lcp_paginator-css" href="https://atmokpo.com/w/wp-content/plugins/list-category-posts//lcp_paginator.css?ver=6.7.2" media="all"> <script src="https://atmokpo.com/w/wp-content/plugins/collapse-magic/js/collapse-magic.js?x=56&amp;ver=1.0" id="claps-main-js"></script> <script defer="" src="https://atmokpo.com/w/wp-content/plugins/koko-analytics/assets/dist/js/script.js?ver=1.6.4" id="koko-analytics-js"></script> <script src="https://atmokpo.com/w/wp-content/plugins/responsive-accordion-and-collapse/js/accordion-custom.js?ver=6.7.2" id="call_ac-custom-js-front-js"></script> <script src="https://atmokpo.com/w/wp-content/plugins/responsive-accordion-and-collapse/js/accordion.js?ver=6.7.2" id="call_ac-js-front-js"></script> <script src="https://stats.wp.com/e-202515.js" id="jetpack-stats-js" data-wp-strategy="defer"></script> <script id="jetpack-stats-js-after"> _stq = window._stq || []; _stq.push([ "view", JSON.parse("{\"v\":\"ext\",\"blog\":\"238449126\",\"post\":\"34690\",\"tz\":\"0\",\"srv\":\"atmokpo.com\",\"j\":\"1:14.2.1\"}") ]); _stq.push([ "clickTrackerInit", "238449126", "34690" ]); </script> <script> document.querySelectorAll("code").forEach(function(codeBlock) { // 내용에 '<'나 '>'가 포함된 경우에만 변환 if (codeBlock.innerHTML.includes("<") && codeBlock.innerHTML.includes(">")) { codeBlock.textContent = codeBlock.innerHTML; } }); </script>