Mr K marsh


Problem Statement :


Mr K has a rectangular plot of land which may have marshes where fenceposts cannot be set. He wants you to find the perimeter of the largest rectangular fence that can be built on this land.

For example, in the following m*n = 4*4 grid, x marks a marsh and . marks good land.

....
..x.
..x.
x...

If we number the rows and columns starting with 1, we see that there are two main areas that can be fenced: (1,1)-(3,2) and (1,2)-(4,4). The longest perimeter is 10.

Function Description

Complete the kMarsh function in the editor below. It should print either an integer or impossible.

kMarsh has the following parameter(s):

grid: an array of strings that represent the grid
Input Format

The first line contains two space-separated integers m and n, the grid rows and columns.
Each of the next m lines contains n characters each describing the state of the land. 'x' (ascii value: 120) if it is a marsh and '.' ( ascii value:46) otherwise.

Constraints
2 <= m,n <= 500

Output Format

Output contains a single integer - the largest perimeter. If the rectangular fence cannot be built, print impossible.



Solution :



title-img


                            Solution in C :

In C++ :





#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int m,n,c=0;
    cin>>m>>n;
    char A[500][500];
    int col[500][500]={0,0},row[500][500]={0,0};
    for(int i=0;i<m;i++)
    {
        for(int j=0;j<n;j++)
        {
            cin>>A[i][j];
        }
    }
    for(int j=0;j<n;j++)
    {
        c=0;
        for(int i=m-1;i>=0;i--)
        {
            if(A[i][j]=='x')
            {
                c=0;
                col[i][j]=c;
            }
            else
            {
                col[i][j]=c;
                c++;
            }
        }
    }
    for(int i=0;i<m;i++)
    {
        c=0;
        for(int j=n-1;j>=0;j--)
        {
            if(A[i][j]=='x')
            {
                c=0;
                row[i][j]=c;
            }
            else
            {
                row[i][j]=c;
                c++;
            }
        }
    }
    /*for(int i=0;i<m;i++)
    {
        for(int j=0;j<n;j++)
        {
            cout<<row[i][j]<<" ";
        }
        cout<<"\n";
    }
    cout<<"\n";
    for(int i=0;i<m;i++)
    {
        for(int j=0;j<n;j++)
        {
            cout<<col[i][j]<<" ";
        }
        cout<<"\n";
    }*/
    int ans=0;
    for(int i=0;i<m;i++)
    {
        for(int j=0;j<n;j++)
        {
            int k,l,lim=row[i][j],mincol;
            for(k=1;k<=lim;k++)
            {
                mincol=min(col[i][j],col[i][j+k]);
                for(l=mincol;l>=1;l--)
                {
                    if(row[i+l][j]>=k)
                        break;
                }
                if(l>0)
                    ans=max(ans,2*(l+k));
            }
        }
    }
    if(ans>0)
        cout<<ans;
    else
        cout<<"impossible";
    return 0;
}








In Java :





import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    static int      m, n;
    static String[] land;

    static int[][]  row;
    static int[][]  col;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        m = in.nextInt();
        n = in.nextInt();
        in.nextLine();
        land = new String[m];
        for (int i = 0; i < m; i++) {
            land[i] = in.nextLine().trim();
        }
        System.out.println(solve());
    }

    private static String solve() {
        row = new int[m][n];
        col = new int[m][n];
        calcReach();
        int max = getMaxPeri();
        if (max == 0) {
            return "impossible";
        } else {
            return max + "";
        }
    }

    private static int getMaxPeri() {
        int max = 0;
        for (int i = m - 1; i > 0; i--) {
            for (int j = n - 1; j > 0; j--) {
                if (land[i].charAt(j) == 'x') {
                    continue;
                }
                int t = getMaxPeri(i, j);
                if (t > max) {
                    max = t;
                }
            }
        }
        return max;
    }

    private static int getMaxPeri(int r, int c) {
        int mr = row[r][c];
        int mc = col[r][c];
        int cc = c;
        int mpr = 0;
        for (int i = mr; i < r; i++) {
            for (int j = mc; j < c && j < cc; j++) {
                if (row[r][j] <= i && col[i][c] <= j) {
                    cc = j;
                    int tp = 2 * (r - i + c - j);
                    if (tp > mpr) {
                        mpr = tp;
                    }
                    break;
                }
            }
        }
        return mpr;
    }

    private static void calcReach() {
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (land[i].charAt(j) == 'x') {
                    row[i][j] = -1;
                    col[i][j] = -1;
                } else {
                    if (j > 0 && land[i].charAt(j - 1) == '.') {
                        col[i][j] = col[i][j - 1];
                    } else {
                        col[i][j] = j;
                    }
                    if (i > 0 && land[i - 1].charAt(j) == '.') {
                        row[i][j] = row[i - 1][j];
                    } else {
                        row[i][j] = i;
                    }
                }
            }
        }
    }

}








In C :





#include <stdio.h>


long long M,a[1000][1000],b[1000],i,j,k,l,m,n,v=0;
char c[1000];


void test(long long aa, long long bb)
{
long long vv;

vv = 2*(aa+bb);

if(vv > v) v = vv;

//printf("test %lld %lld\n", aa,bb);

return ;
}

int main()
{

scanf("%lld %lld",&M, &n);


for(i=0;i<M;i++)
    {
     scanf("%s",c);
     for(j=0;j<n;j++) 
     {
//       printf("-%c\n",c[j]);
       if(c[j]=='.') a[i][j] = 0; else a[i][j] = 1;
     }   
     
    }
/*
for(i=0;i<M;i++)
{

 for(j=0;j<n;j++) 
    {
 printf("%lld ",a[i][j]);
    }

printf("\n");
}
*/

for(i=1;i<M;i++)
{
for(j=0;j<=i;j++) b[j] = -1;
 
 for(j=0;j<n;j++)
  {

//printf("%lld =i %lld =j\n",i,j);
//for(m=i-1;m>=0;m--) printf("m=%lld -> %lld\n",m,b[m]);


   k = a[i][j];
  
   for(m=i-1;m>=0;m--)
     {
       if(a[i][j]) b[m] = -1;
     
       if(a[m][j] == 1) 
         {
           k = 1;
           b[m] = -1;
           continue;
         }
      
       if(k==0 && b[m]!=-1) test(i-m,j-b[m]);
     
       if(k==0 && b[m] == -1) b[m] = j;        
     
     }
  
  
  }
}

if(v) printf("%lld\n",v);
 else printf("impossible\n");

return 0;
}








In Python3 :





N,M=map(int,input().split())
up=[[0 for i in range(M)]for n in range(N)]
left=[]
land=[[x for x in input()] for i in range(N)]
for i in range(N):
    left.append([0 for x in range(M)])
    for j in range(M):
        if j==0:
            left[i][j]=0 if land[i][j]!='x' else -1
        elif land[i][j]=='x':
            left[i][j]=-1
        else:
            left[i][j]=left[i][j-1]+1
for i in range(M):
    for j in range(N):
        if j==0:
            up[j][i]=0 if land[j][i]!='x' else -1
        elif land[j][i]=='x':
            up[j][i]=-1
        else:
            up[j][i]=up[j-1][i]+1
max_perimeter=-1
for row in range(N-1,0,-1):
    for column in range(M-1,0,-1):
        for k in range(column-left[row][column],column):
            for temp in range(1,min(up[row][column],up[row][k])+1):
                if left[row-temp][column]>=(column-k):
                    max_perimeter=max(max_perimeter,2*(temp+column-k))
print(max_perimeter if max_perimeter>0 else 'impossible')
                        








View More Similar Problems

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →

Unique Colors

You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti

View Solution →

Fibonacci Numbers Tree

Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T

View Solution →

Pair Sums

Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v

View Solution →

Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

View Solution →