Program Explanation

This program finds the largest square containing only 1s in a given binary matrix (2D slice).
It uses dynamic programming to keep track of the size of the largest square that can be formed
at each cell in the matrix.

Program Structure

  1. Function Definition: The main function is maximalSquare(matrix [][]byte) int,
    which takes a 2D slice of bytes representing the binary matrix.
  2. Dynamic Programming Table: A DP table is created to store the size of the largest square
    that ends at each position.
  3. Logic: As we iterate through each cell in the matrix, we check if the cell contains a ‘1’.
    If it does, we compute the minimum of the three adjacent squares (top, left, and top-left diagonal)
    to determine the size of the largest square that can be formed at that position.
  4. Result: The maximum size found during the iteration is returned as the area of the largest
    square.

Go Code


package main

import (
    "fmt"
)

// maximalSquare finds the largest square containing only 1s in a binary matrix.
func maximalSquare(matrix [][]byte) int {
    if len(matrix) == 0 || len(matrix[0]) == 0 {
        return 0
    }

    maxSide := 0
    rows := len(matrix)
    cols := len(matrix[0])
    
    // Create a DP array to store the size of the largest square
    dp := make([][]int, rows)
    for i := range dp {
        dp[i] = make([]int, cols)
    }

    // Iterate through the matrix
    for i := 0; i < rows; i++ {
        for j := 0; j < cols; j++ { if matrix[i][j] == '1' { // Check the top, left, and top-left diagonal squares if i == 0 || j == 0 { dp[i][j] = 1 // First row or column } else { dp[i][j] = min(dp[i-1][j], min(dp[i][j-1], dp[i-1][j-1])) + 1 } // Update the maximum side length if dp[i][j] > maxSide {
                    maxSide = dp[i][j]
                }
            }
        }
    }

    // The area of the largest square
    return maxSide * maxSide
}

// min returns the minimum of two integers.
func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}

func main() {
    // Example binary matrix
    matrix := [][]byte{
        {'1', '0', '1', '0', '0'},
        {'1', '0', '1', '1', '1'},
        {'1', '1', '1', '1', '1'},
        {'1', '0', '0', '1', '0'},
    }

    result := maximalSquare(matrix)
    fmt.Printf("The area of the largest square is: %d\n", result)
}

Explanation of the Code:

  • Function maximalSquare(matrix [][]byte) int: This is the main function that takes a binary matrix as input and returns the area of the largest square containing only 1s.
  • Dynamic Programming Table (dp): A 2D slice is created to keep track of the largest square size that can be formed at each position.
  • Logic for Size Calculation: For each cell with a ‘1’, the size of the square is calculated based on the minimum value of the adjacent cells (top, left, and top-left diagonal).
  • Result Calculation: The maximum size found is used to calculate the area of the largest square.
  • Function min(a, b int) int: A utility function to find the minimum of two integers.

How to Run the Program:

  1. Save the code as main.go.
  2. Open your terminal and navigate to the directory containing the file.
  3. Run the command go run main.go.

Conclusion

This Go program effectively utilizes dynamic programming to solve the problem of finding the largest square
containing only 1s in a binary matrix. The approach ensures efficiency by reducing the need for redundant calculations.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)