{"id":33540,"date":"2024-11-01T09:17:39","date_gmt":"2024-11-01T09:17:39","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=33540"},"modified":"2024-11-01T11:38:03","modified_gmt":"2024-11-01T11:38:03","slug":"java-coding-test-course-finding-cities-at-a-specific-distance","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/33540\/","title":{"rendered":"Java Coding Test Course, Finding Cities at a Specific Distance"},"content":{"rendered":"<p>Hello, everyone! Today, we will be tackling algorithm problems for job preparation using Java. The topic this time is &#8220;Finding Cities at a Specific Distance,&#8221; utilizing graph theory and the BFS (Breadth-First Search) algorithm. We will delve deep into the fundamental concepts of algorithms and how to effectively use Java\u2019s useful data structures while solving this problem.<\/p>\n<h2>Problem Description<\/h2>\n<p>The given cities are interconnected by roads, and each city is marked with a number. The task is to find and return all cities that can be reached by traveling a specific distance K starting from city number 1. Thus, the input consists of the number of cities N, the number of roads M, the starting city X, and the target distance K, and the output should be the city numbers sorted in ascending order.<\/p>\n<h3>Input<\/h3>\n<ul>\n<li>First line: Number of cities N (1 \u2264 N \u2264 30000), number of roads M (1 \u2264 M \u2264 200000)<\/li>\n<li>Second line: Starting city number X (1 \u2264 X \u2264 N) and target distance K (0 \u2264 K \u2264 30000)<\/li>\n<li>Next M lines: Two connected cities A, B (1 \u2264 A, B \u2264 N, A \u2260 B)<\/li>\n<\/ul>\n<h3>Output<\/h3>\n<p>Print the numbers of the cities that can be reached at the target distance K in ascending order. If there are no reachable cities, print -1.<\/p>\n<h2>Solution Approach<\/h2>\n<p>To solve this problem, we need to construct a graph and use the BFS algorithm to find the cities reachable by the given distance K. BFS is suitable for this as it visits all vertices of the graph in level order, which helps in reaching cities at a specific distance.<\/p>\n<h3>Step 1: Graph Representation<\/h3>\n<p>We use an adjacency list to represent the road relationships between cities. In Java, we can utilize <code>ArrayList<\/code> to store adjacent cities for each city. This minimizes memory use and makes it easy to manage the relationships between cities.<\/p>\n<h3>Step 2: Implementing BFS<\/h3>\n<p>To implement BFS, we use a queue to store the current city and the current distance, continuing the search until this distance reaches K. Care should be taken not to revisit cities that have already been visited during the search process. Additionally, we must compare the current distance accurately with K.<\/p>\n<h3>Step 3: Output the Results<\/h3>\n<p>After collecting the cities that reached the target distance K, we sort them in ascending order and print them. If no city was reachable, we print -1.<\/p>\n<h2>Java Code Example<\/h2>\n<pre><code>\nimport java.util.*;\n\npublic class SpecificDistanceCity {\n    static ArrayList<Integer>[] graph;\n    static boolean[] visited;\n    static int[] distance;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n\n        int N = sc.nextInt(); \/\/ Number of cities\n        int M = sc.nextInt(); \/\/ Number of roads\n        int X = sc.nextInt(); \/\/ Starting city\n        int K = sc.nextInt(); \/\/ Target distance\n\n        \/\/ Initialize the graph\n        graph = new ArrayList[N + 1];\n        for (int i = 1; i <= N; i++) {\n            graph[i] = new ArrayList<>();\n        }\n\n        \/\/ Input road information\n        for (int i = 0; i < M; i++) {\n            int A = sc.nextInt();\n            int B = sc.nextInt();\n            graph[A].add(B);\n        }\n\n        \/\/ Output the results\n        List<Integer> result = bfs(X, K);\n        if (result.isEmpty()) {\n            System.out.println(-1);\n        } else {\n            Collections.sort(result);\n            for (int city : result) {\n                System.out.println(city);\n            }\n        }\n\n        sc.close();\n    }\n\n    private static List<Integer> bfs(int start, int targetDistance) {\n        List<Integer> reachableCities = new ArrayList<>();\n        Queue<int[]> queue = new LinkedList<>(); \/\/ City and current distance\n        visited = new boolean[graph.length];\n        distance = new int[graph.length];\n\n        queue.offer(new int[]{start, 0}); \/\/ (city, distance)\n        visited[start] = true;\n\n        while (!queue.isEmpty()) {\n            int[] current = queue.poll();\n            int currentCity = current[0];\n            int currentDistance = current[1];\n\n            \/\/ Add city when reaching target distance\n            if (currentDistance == targetDistance) {\n                reachableCities.add(currentCity);\n            }\n\n            \/\/ Move to the next distance\n            for (int neighbor : graph[currentCity]) {\n                if (!visited[neighbor] && currentDistance + 1 <= targetDistance) {\n                    visited[neighbor] = true;\n                    queue.offer(new int[]{neighbor, currentDistance + 1});\n                }\n            }\n        }\n\n        return reachableCities;\n    }\n}\n<\/int[]><\/Integer><\/Integer><\/Integer><\/Integer><\/code><\/pre>\n<h2>Code Explanation<\/h2>\n<p>The code above can be divided into three main parts. The main function initializes the graph and inputs the road information, then explores reachable cities using BFS. The BFS function uses a queue to manage the current city and distance and adds the city to the result list when it reaches the target. After all BFS explorations are completed, it sorts and outputs the reachable cities.<\/p>\n<h2>Try It Yourself<\/h2>\n<p>Now it&#8217;s your turn to run the code. Test with various input data to verify if the desired output is achieved. Additionally, try adding comments or modifying conditions in different parts of the code to experiment with its functionality. This will deepen your understanding of the algorithm.<\/p>\n<h2>Conclusion<\/h2>\n<p>Through this lecture, we learned the basic BFS algorithm and how to implement graphs to solve the problem of finding cities at a specific distance. As employment is the goal, I hope you solve many of these problems and build your skills. In the next lecture, we will tackle a more challenging topic. Thank you!<\/p>\n<footer>\n<p>Author: Java Coding Test Course<\/p>\n<p>Contact: example@example.com<\/p>\n<\/footer>\n","protected":false},"excerpt":{"rendered":"<p>Hello, everyone! Today, we will be tackling algorithm problems for job preparation using Java. The topic this time is &#8220;Finding Cities at a Specific Distance,&#8221; utilizing graph theory and the BFS (Breadth-First Search) algorithm. We will delve deep into the fundamental concepts of algorithms and how to effectively use Java\u2019s useful data structures while solving &hellip; <a href=\"https:\/\/atmokpo.com\/w\/33540\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Java Coding Test Course, Finding Cities at a Specific Distance&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[139],"tags":[],"class_list":["post-33540","post","type-post","status-publish","format-standard","hentry","category-java-coding-test"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Java Coding Test Course, Finding Cities at a Specific Distance - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/atmokpo.com\/w\/33540\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Coding Test Course, Finding Cities at a Specific Distance - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"Hello, everyone! Today, we will be tackling algorithm problems for job preparation using Java. The topic this time is &#8220;Finding Cities at a Specific Distance,&#8221; utilizing graph theory and the BFS (Breadth-First Search) algorithm. We will delve deep into the fundamental concepts of algorithms and how to effectively use Java\u2019s useful data structures while solving &hellip; \ub354 \ubcf4\uae30 &quot;Java Coding Test Course, Finding Cities at a Specific Distance&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/33540\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:17:39+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:38:03+00:00\" \/>\n<meta name=\"author\" content=\"root\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:site\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:label1\" content=\"\uae00\uc4f4\uc774\" \/>\n\t<meta name=\"twitter:data1\" content=\"root\" \/>\n\t<meta name=\"twitter:label2\" content=\"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04\" \/>\n\t<meta name=\"twitter:data2\" content=\"2\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/33540\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33540\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Java Coding Test Course, Finding Cities at a Specific Distance\",\"datePublished\":\"2024-11-01T09:17:39+00:00\",\"dateModified\":\"2024-11-01T11:38:03+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33540\/\"},\"wordCount\":575,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"Java Coding Test\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/33540\/\",\"url\":\"https:\/\/atmokpo.com\/w\/33540\/\",\"name\":\"Java Coding Test Course, Finding Cities at a Specific Distance - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:17:39+00:00\",\"dateModified\":\"2024-11-01T11:38:03+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33540\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/33540\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/33540\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java Coding Test Course, Finding Cities at a Specific Distance\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/atmokpo.com\/w\/#website\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/atmokpo.com\/w\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"contentUrl\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"width\":400,\"height\":400,\"caption\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\"},\"image\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/bebubo4\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\",\"name\":\"root\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"caption\":\"root\"},\"sameAs\":[\"http:\/\/atmokpo.com\/w\"],\"url\":\"https:\/\/atmokpo.com\/w\/author\/root\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java Coding Test Course, Finding Cities at a Specific Distance - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/atmokpo.com\/w\/33540\/","og_locale":"ko_KR","og_type":"article","og_title":"Java Coding Test Course, Finding Cities at a Specific Distance - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"Hello, everyone! Today, we will be tackling algorithm problems for job preparation using Java. The topic this time is &#8220;Finding Cities at a Specific Distance,&#8221; utilizing graph theory and the BFS (Breadth-First Search) algorithm. We will delve deep into the fundamental concepts of algorithms and how to effectively use Java\u2019s useful data structures while solving &hellip; \ub354 \ubcf4\uae30 \"Java Coding Test Course, Finding Cities at a Specific Distance\"","og_url":"https:\/\/atmokpo.com\/w\/33540\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:17:39+00:00","article_modified_time":"2024-11-01T11:38:03+00:00","author":"root","twitter_card":"summary_large_image","twitter_creator":"@bebubo4","twitter_site":"@bebubo4","twitter_misc":{"\uae00\uc4f4\uc774":"root","\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04":"2\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/33540\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/33540\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Java Coding Test Course, Finding Cities at a Specific Distance","datePublished":"2024-11-01T09:17:39+00:00","dateModified":"2024-11-01T11:38:03+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/33540\/"},"wordCount":575,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["Java Coding Test"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/33540\/","url":"https:\/\/atmokpo.com\/w\/33540\/","name":"Java Coding Test Course, Finding Cities at a Specific Distance - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:17:39+00:00","dateModified":"2024-11-01T11:38:03+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/33540\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/33540\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/33540\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Java Coding Test Course, Finding Cities at a Specific Distance"}]},{"@type":"WebSite","@id":"https:\/\/atmokpo.com\/w\/#website","url":"https:\/\/atmokpo.com\/w\/","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","description":"","publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/atmokpo.com\/w\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/atmokpo.com\/w\/#organization","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","url":"https:\/\/atmokpo.com\/w\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/","url":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","contentUrl":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","width":400,"height":400,"caption":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8"},"image":{"@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/bebubo4"]},{"@type":"Person","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7","name":"root","image":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","caption":"root"},"sameAs":["http:\/\/atmokpo.com\/w"],"url":"https:\/\/atmokpo.com\/w\/author\/root\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/33540","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/comments?post=33540"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/33540\/revisions"}],"predecessor-version":[{"id":33541,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/33540\/revisions\/33541"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=33540"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=33540"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=33540"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}