Swift Coding Test Course, Find the Largest Square

Algorithm problems play an important role in developing problem-solving skills for programmers. In this article, we will address the problem of finding the largest square using Swift. The goal is to find the area of the largest square in a given 2D array.

Problem Description

Given a binary matrix, write a function to find the largest square containing only 1s and return its area. 0 represents an empty cell, and 1 represents a filled cell.

Example

Input:
[
    [1, 0, 1, 0, 0],
    [1, 0, 1, 1, 1],
    [1, 1, 1, 1, 1],
    [1, 0, 0, 1, 0]
]

Output: 4

Problem Solving Process

Approach to the Problem

To solve this problem, we will use a dynamic programming approach. Below are the steps to tackle the problem.

  1. Create a DP table based on the given binary matrix.
  2. Calculate the size of the largest square at each cell.
  3. More specifically, while traversing each element of the matrix, if that element is 1, update it to be the minimum value of the element to the right, below, and diagonally below plus one.
  4. Calculate and return the area of the largest square found.

Dynamic Programming Table Construction

The size of the DP table will be the same as the input matrix, and the values at each element will be set according to the following rules.

  • If it is 0: Set to 0 since no square can be formed at that position.
  • If it is 1: Calculate the size of the square by referencing the adjacent values as described above.

Swift Code Implementation

Now let’s implement the approach described above in Swift code.


func maximalSquare(_ matrix: [[Character]]) -> Int {
    guard !matrix.isEmpty else { return 0 }
    let rows = matrix.count
    let cols = matrix[0].count
    var dp = Array(repeating: Array(repeating: 0, count: cols), count: rows)
    var maxSide = 0

    for i in 0..<rows {="" for="" j="" in="" 0..<cols="" if="" i="=" 0="" ||="" dp[i][j]="matrix[i][j]" =="1" ?="" 1="" :="" }="" else="" matrix[i][j]="=" "1"="" dp[i][j-1],="" dp[i-1][j-1])="" +="" maxside="max(maxSide," dp[i][j])="" return="" *="" <="" code=""></rows>
<h3>Code Explanation</h3> <p>Let me explain all the variables used in the code above:</p> <ul> <li><strong>rows</strong>: The number of rows in the matrix</li> <li><strong>cols</strong>: The number of columns in the matrix</li> <li><strong>dp</strong>: The dynamic programming table storing the size of each square</li> <li><strong>maxSide</strong>: The length of the side of the largest square found so far</li> </ul> <h3>Test Cases</h3> <p>Now let's test the code we wrote. Below are some test cases.</p> <pre><code> let testMatrix1: [[Character]] = [ ["1", "0", "1", "0", "0"], ["1", "0", "1", "1", "1"], ["1", "1", "1", "1", "1"], ["1", "0", "0", "1", "0"] ] let result1 = maximalSquare(testMatrix1) print(result1) // 4 let testMatrix2: [[Character]] = [ ["0", "1"], ["1", "0"] ] let result2 = maximalSquare(testMatrix2) print(result2) // 1 </code></pre> <h3>Conclusion</h3> <p>In this tutorial, we learned how to solve the problem of finding the largest square using Swift. This problem can be efficiently solved through the application of dynamic programming and is commonly encountered in coding interviews. Solving real algorithm problems is very beneficial, and I hope that through practice, you can elevate your problem-solving skills to the next level.</p> <h2>References</h2> <p>If you want to learn more about this problem in depth, please refer to the following resources:</p> <ul> <li><a href="https://www.geeksforgeeks.org/largest-square-formed-in-a-matrix/" target="_blank" rel="noopener">Largest Square Formed in a Matrix - GeeksforGeeks</a></li> <li><a href="https://leetcode.com/problems/maximal-square/" target="_blank" rel="noopener">Maximal Square - LeetCode</a></li> <li><a href="https://medium.com/swlh/understanding-dynamic-programming-with-maximum-square-14eb7d9f6548" target="_blank" rel="noopener">Understanding Dynamic Programming with Maximum Square - Medium</a></li> </ul> <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/34672/" rel="bookmark"><time class="entry-date published" datetime="2024-11-01T09:30:43+00:00">2024/11/01</time><time class="updated" datetime="2024-11-01T11:27:03+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/34670/" 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 Fastest Bus Route</span></a></div><div class="nav-next"><a href="https://atmokpo.com/w/34674/" 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, I Don’t Want to Be a Liar</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/34896/">Swift Coding Test Course, Tree Traversal</a></li><li><a href="https://atmokpo.com/w/34894/">Swift Coding Test Course, Try</a></li><li><a href="https://atmokpo.com/w/34892/">Swift Coding Test Course, Two Pointers</a></li><li><a href="https://atmokpo.com/w/34890/">Swift Coding Test Course, Preparing for Resignation</a></li><li><a href="https://atmokpo.com/w/34888/">Swift Coding Test Course, Fast Travel with Time Machine</a></li><li><a href="https://atmokpo.com/w/34886/">Swift Coding Test Course, Quick Sort</a></li><li><a href="https://atmokpo.com/w/34884/">Swift Coding Test Course, Kevin Bacon’s 6 Degrees of Separation</a></li><li><a href="https://atmokpo.com/w/34882/">Swift Coding Test Course, Cocktail Making</a></li><li><a href="https://atmokpo.com/w/34880/">Swift Coding Test Course, Card Sorting</a></li><li><a href="https://atmokpo.com/w/34878/">Swift Coding Test Course, Card Game</a></li></ul><ul class="lcp_paginator"><li><a href="https://atmokpo.com/w/34672/?lcp_pagelistcategorypostswidget-3=1#lcp_instance_listcategorypostswidget-3" title="1" class="lcp_prevlink">&lt;&lt;</a></li><li><a href="https://atmokpo.com/w/34672/?lcp_pagelistcategorypostswidget-3=1#lcp_instance_listcategorypostswidget-3" title="1">1</a></li><li class="lcp_currentpage">2</li><li><a href="https://atmokpo.com/w/34672/?lcp_pagelistcategorypostswidget-3=3#lcp_instance_listcategorypostswidget-3" title="3">3</a></li><li><a href="https://atmokpo.com/w/34672/?lcp_pagelistcategorypostswidget-3=4#lcp_instance_listcategorypostswidget-3" title="4">4</a></li><li><a href="https://atmokpo.com/w/34672/?lcp_pagelistcategorypostswidget-3=5#lcp_instance_listcategorypostswidget-3" title="5">5</a></li><li><a href="https://atmokpo.com/w/34672/?lcp_pagelistcategorypostswidget-3=6#lcp_instance_listcategorypostswidget-3" title="6">6</a></li><li><a href="https://atmokpo.com/w/34672/?lcp_pagelistcategorypostswidget-3=7#lcp_instance_listcategorypostswidget-3" title="7">7</a></li><span class="lcp_elipsis">...</span><li><a href="https://atmokpo.com/w/34672/?lcp_pagelistcategorypostswidget-3=14#lcp_instance_listcategorypostswidget-3" title="14">14</a></li><li><a href="https://atmokpo.com/w/34672/?lcp_pagelistcategorypostswidget-3=3#lcp_instance_listcategorypostswidget-3" title="3" 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=145&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\":\"34672\",\"tz\":\"0\",\"srv\":\"atmokpo.com\",\"j\":\"1:14.2.1\"}") ]); _stq.push([ "clickTrackerInit", "238449126", "34672" ]); </script> <script> document.querySelectorAll("code").forEach(function(codeBlock) { // 내용에 '<'나 '>'가 포함된 경우에만 변환 if (codeBlock.innerHTML.includes("<") && codeBlock.innerHTML.includes(">")) { codeBlock.textContent = codeBlock.innerHTML; } }); </script>