💻 Largest Square of 1s in Binary Matrix with DP
Discover dynamic programming to find the maximal square of land in a watery matrix — input your grid and uncover the largest island square!
🗺️ The Land Surveyor's Quest
🎯 The Challenge:
You are given a binary matrix representing a piece of land, where each cell contains either a 1 (land) or a 0 (water). Your task is to identify the largest square sub-matrix that contains only 1s, and print the coordinates of its top-left cell along with the size of the square.
📋 Problem:
Write a program in C++ that reads a matrix from input, processes it using dynamic programming, and finds the largest square region fully composed of land (1s). If there are multiple squares of the same maximum size, print the one that appears first in top-to-bottom, left-to-right order.
Problem Specifications
- Input: First line: two integers R and C (1 ≤ R, C ≤ 1000). Next R lines: C space-separated 0s or 1s.
- Output: Three integers: row index, column index (0-based) of top-left corner, and size of the square.
Example: Input 1
3 3 1 1 1 1 1 1 1 1 1
Output: 0 0 3
Example: Input 2
4 5 0 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 0 0 0 0
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 1 | 1 | 0 |
| 0 | 1 | 1 | 1 | 0 |
| 0 | 0 | 0 | 0 | 0 |
Output: 1 1 2
🔄 Dynamic Programming Strategy
Key Idea
- Create a DP table where dp[i][j] = size of largest square with bottom-right at (i,j).
- For boundaries: dp[i][0] = matrix[i][0], dp[0][j] = matrix[0][j].
- For others: if matrix[i][j] == 1, dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1; else 0.
- Track max size and top-left position (scan top-to-bottom, left-to-right).
Note: Top-left of square is (i - size + 1, j - size + 1).
DP Table Fill
Time: O(R * C)
Brute Force
Check all squares: O(R^2 * C^2)
🔍 Step-by-Step DP Demo
Original Matrix
DP Table State (size at bottom-right)
Click Start to run demo
Progress Tracker
🎮 Build Your Maximal Square Finder
DP Table & Max Square Highlight
Examples
📊 Analysis & Optimization
Time
O(R * C)
Each cell processed in constant time.
Space
O(R * C)
For DP table; optimizable to O(C).
Optimization Ideas
- Use 1D array for space optimization (update in-place).
- Early exit if max size == min(R,C).
- Fast I/O for large 1000x1000 inputs in C++.