Más grande o '+' formado por todos los unos en una matriz cuadrada binaria

Más grande o '+' formado por todos los unos en una matriz cuadrada binaria

dado un norte × norte matriz binaria junto con consistente en 0s y 1s . Tu tarea es encontrar el tamaño del más grande. '+' forma que se puede formar usando sólo 1s .

signo más

A '+' La forma consta de una celda central con cuatro brazos que se extienden en las cuatro direcciones ( arriba abajo izquierda y derecha ) mientras permanece dentro de los límites de la matriz. El tamaño de un '+' se define como el número total de células formándolo incluyendo el centro y todos los brazos.

La tarea es devolver el tamaño máximo de cualquier válido '+' en junto con . si no '+' se puede formar retorno .

Ejemplos:

Aporte: con = [ [0 1 1 0 1] [0 0 1 1 1] [1 1 1 1 1] [1 1 1 0 1] [0 1 1 1 0] ]
Producción: 9
Explicación: Se puede formar un "+" con una longitud de brazo de 2 (2 celdas en cada dirección + 1 centro) en el centro del tapete.
0 1 1 0 1
0 0 1 1 1
1 1 1 1 1
1 1 1 0 1
0 1 1 1 0
Tamaño total = (2 × 4) + 1 = 9

Aporte: con = [ [0 1 1] [0 0 1] [1 1 1] ]
Producción: 1
Explicación: Se puede formar un '+' con una longitud de brazo de 0 (0 celdas en cada dirección + 1 centro) con cualquiera de los 1.

Aporte: con = [[0]]
Producción:
Explicación: No Se puede formar el signo "+".

[Enfoque ingenuo] - Considere cada punto como centro - O(n^4) Tiempo y O(n^4) Espacio

Atraviese las celdas de la matriz una por una. Considere cada punto atravesado como centro de un más y encuentre el tamaño del +. Para cada elemento recorremos de izquierda a derecha, abajo y arriba. El peor caso en esta solución ocurre cuando tenemos todos los 1.

[Enfoque esperado] - Precalcular 4 matrices - O(n^2) Tiempo y O(n^2) Espacio

El idea es mantener cuatro matrices auxiliares izquierda[][] derecha[][] arriba[][] abajo[][] para almacenar unos consecutivos en todas las direcciones. Para cada celda (yo j) en la matriz de entrada almacenamos la siguiente información en estos cuatro matrices -

  • izquierda (i j) almacena el número máximo de unos consecutivos en el izquierda de la celda (i j) incluida la celda (i j).
  • derecha (i j) almacena el número máximo de unos consecutivos en el bien de la celda (i j) incluida la celda (i j).
  • arriba (i j) almacena el número máximo de unos consecutivos en arriba de la celda (i j) incluida la celda (i j).
  • abajo (i j) almacena el número máximo de unos consecutivos en abajo de la celda (i j) incluida la celda (i j).

Después de calcular el valor para cada celda de las matrices anteriores, mayor'+' estaría formado por una celda de la matriz de entrada que tiene valor máximo considerando el mínimo de ( izquierda (i j) derecha (i j) arriba (i j) abajo (i j) )

podemos usar Programación dinámica para calcular la cantidad total de unos consecutivos en cada dirección:

si mat(i j) == 1
izquierda(i j) = izquierda(i j - 1) + 1


si mat(i j) == 1
arriba(i j) = arriba(i - 1 j) + 1;

de lo contrario arriba(i j) = 0;


si mat(i j) == 1
abajo(i j) = abajo(i + 1 j) + 1;

de lo contrario abajo (i j) = 0;


si mat(i j) == 1
derecha(i j) = derecha(i j + 1) + 1;

de lo contrario, derecha (i j) = 0;

A continuación se muestra la implementación del enfoque anterior:

C++
   // C++ program to find the largest '+' in a binary matrix   // using Dynamic Programming   #include          using     namespace     std  ;   int     findLargestPlus  (  vector   <  vector   <  int  >>     &  mat  )     {          int     n     =     mat  .  size  ();          vector   <  vector   <  int  >>     left  (  n       vector   <  int  >  (  n       0  ));      vector   <  vector   <  int  >>     right  (  n       vector   <  int  >  (  n       0  ));      vector   <  vector   <  int  >>     top  (  n       vector   <  int  >  (  n       0  ));      vector   <  vector   <  int  >>     bottom  (  n       vector   <  int  >  (  n       0  ));          // Fill left and top matrices      for     (  int     i     =     0  ;     i      <     n  ;     i  ++  )     {      for     (  int     j     =     0  ;     j      <     n  ;     j  ++  )     {      if     (  mat  [  i  ][  j  ]     ==     1  )     {      left  [  i  ][  j  ]     =     (  j     ==     0  )     ?     1     :     left  [  i  ][  j     -     1  ]     +     1  ;      top  [  i  ][  j  ]     =     (  i     ==     0  )     ?     1     :     top  [  i     -     1  ][  j  ]     +     1  ;      }      }      }          // Fill right and bottom matrices      for     (  int     i     =     n     -     1  ;     i     >=     0  ;     i  --  )     {      for     (  int     j     =     n     -     1  ;     j     >=     0  ;     j  --  )     {      if     (  mat  [  i  ][  j  ]     ==     1  )     {      right  [  i  ][  j  ]     =     (  j     ==     n     -     1  )     ?     1     :     right  [  i  ][  j     +     1  ]     +     1  ;      bottom  [  i  ][  j  ]     =     (  i     ==     n     -     1  )     ?     1     :     bottom  [  i     +     1  ][  j  ]     +     1  ;      }      }      }          int     maxPlusSize     =     0  ;          // Compute the maximum '+' size      for     (  int     i     =     0  ;     i      <     n  ;     i  ++  )     {      for     (  int     j     =     0  ;     j      <     n  ;     j  ++  )     {      if     (  mat  [  i  ][  j  ]     ==     1  )     {      int     armLength     =     min  ({  left  [  i  ][  j  ]     right  [  i  ][  j  ]      top  [  i  ][  j  ]     bottom  [  i  ][  j  ]});          maxPlusSize     =     max  (  maxPlusSize        (  4     *     (  armLength     -     1  ))     +     1  );      }      }      }          return     maxPlusSize  ;   }   int     main  ()     {          // Hardcoded input matrix      vector   <  vector   <  int  >>     mat     =     {      {  0       1       1       0       1  }      {  0       0       1       1       1  }      {  1       1       1       1       1  }      {  1       1       1       0       1  }      {  0       1       1       1       0  }      };          cout      < <     findLargestPlus  (  mat  )      < <     endl  ;      return     0  ;   }   
Java
   // Java program to find the largest '+' in a binary matrix   // using Dynamic Programming   class   GfG     {          static     int     findLargestPlus  (  int  [][]     mat  )     {          int     n     =     mat  .  length  ;          int  [][]     left     =     new     int  [  n  ][  n  ]  ;      int  [][]     right     =     new     int  [  n  ][  n  ]  ;      int  [][]     top     =     new     int  [  n  ][  n  ]  ;      int  [][]     bottom     =     new     int  [  n  ][  n  ]  ;          // Fill left and top matrices      for     (  int     i     =     0  ;     i      <     n  ;     i  ++  )     {      for     (  int     j     =     0  ;     j      <     n  ;     j  ++  )     {      if     (  mat  [  i  ][  j  ]     ==     1  )     {      left  [  i  ][  j  ]     =     (  j     ==     0  )     ?     1     :     left  [  i  ][  j     -     1  ]     +     1  ;      top  [  i  ][  j  ]     =     (  i     ==     0  )     ?     1     :     top  [  i     -     1  ][  j  ]     +     1  ;      }      }      }          // Fill right and bottom matrices      for     (  int     i     =     n     -     1  ;     i     >=     0  ;     i  --  )     {      for     (  int     j     =     n     -     1  ;     j     >=     0  ;     j  --  )     {      if     (  mat  [  i  ][  j  ]     ==     1  )     {      right  [  i  ][  j  ]     =     (  j     ==     n     -     1  )     ?     1     :     right  [  i  ][  j     +     1  ]     +     1  ;      bottom  [  i  ][  j  ]     =     (  i     ==     n     -     1  )     ?     1     :     bottom  [  i     +     1  ][  j  ]     +     1  ;      }      }      }          int     maxPlusSize     =     0  ;          // Compute the maximum '+' size      for     (  int     i     =     0  ;     i      <     n  ;     i  ++  )     {      for     (  int     j     =     0  ;     j      <     n  ;     j  ++  )     {      if     (  mat  [  i  ][  j  ]     ==     1  )     {      int     armLength     =     Math  .  min  (  Math  .  min  (  left  [  i  ][  j  ]       right  [  i  ][  j  ]  )      Math  .  min  (  top  [  i  ][  j  ]       bottom  [  i  ][  j  ]  ));          maxPlusSize     =     Math  .  max  (  maxPlusSize        (  4     *     (  armLength     -     1  ))     +     1  );      }      }      }          return     maxPlusSize  ;      }      public     static     void     main  (  String  []     args  )     {          // Hardcoded input matrix      int  [][]     mat     =     {      {  0       1       1       0       1  }      {  0       0       1       1       1  }      {  1       1       1       1       1  }      {  1       1       1       0       1  }      {  0       1       1       1       0  }      };          System  .  out  .  println  (  findLargestPlus  (  mat  ));      }   }   
Python
   # Python program to find the largest '+' in a binary matrix   # using Dynamic Programming   def   findLargestPlus  (  mat  ):   n   =   len  (  mat  )   left   =   [[  0  ]   *   n   for   i   in   range  (  n  )]   right   =   [[  0  ]   *   n   for   i   in   range  (  n  )]   top   =   [[  0  ]   *   n   for   i   in   range  (  n  )]   bottom   =   [[  0  ]   *   n   for   i   in   range  (  n  )]   # Fill left and top matrices   for   i   in   range  (  n  ):   for   j   in   range  (  n  ):   if   mat  [  i  ][  j  ]   ==   1  :   left  [  i  ][  j  ]   =   1   if   j   ==   0   else   left  [  i  ][  j   -   1  ]   +   1   top  [  i  ][  j  ]   =   1   if   i   ==   0   else   top  [  i   -   1  ][  j  ]   +   1   # Fill right and bottom matrices   for   i   in   range  (  n   -   1     -  1     -  1  ):   for   j   in   range  (  n   -   1     -  1     -  1  ):   if   mat  [  i  ][  j  ]   ==   1  :   right  [  i  ][  j  ]   =   1   if   j   ==   n   -   1   else   right  [  i  ][  j   +   1  ]   +   1   bottom  [  i  ][  j  ]   =   1   if   i   ==   n   -   1   else   bottom  [  i   +   1  ][  j  ]   +   1   maxPlusSize   =   0   # Compute the maximum '+' size   for   i   in   range  (  n  ):   for   j   in   range  (  n  ):   if   mat  [  i  ][  j  ]   ==   1  :   armLength   =   min  (  left  [  i  ][  j  ]   right  [  i  ][  j  ]   top  [  i  ][  j  ]   bottom  [  i  ][  j  ])   maxPlusSize   =   max  (  maxPlusSize     (  4   *   (  armLength   -   1  ))   +   1  )   return   maxPlusSize   if   __name__   ==   '__main__'  :   # Hardcoded input matrix   mat   =   [   [  0     1     1     0     1  ]   [  0     0     1     1     1  ]   [  1     1     1     1     1  ]   [  1     1     1     0     1  ]   [  0     1     1     1     0  ]   ]   print  (  findLargestPlus  (  mat  ))   
C#
   // C# program to find the largest '+' in a binary matrix   // using Dynamic Programming   using     System  ;   class     GfG     {          static     int     FindLargestPlus  (  int  []     mat  )     {          int     n     =     mat  .  GetLength  (  0  );          int  []     left     =     new     int  [  n       n  ];      int  []     right     =     new     int  [  n       n  ];      int  []     top     =     new     int  [  n       n  ];      int  []     bottom     =     new     int  [  n       n  ];          // Fill left and top matrices      for     (  int     i     =     0  ;     i      <     n  ;     i  ++  )     {      for     (  int     j     =     0  ;     j      <     n  ;     j  ++  )     {      if     (  mat  [  i       j  ]     ==     1  )     {      left  [  i       j  ]     =     (  j     ==     0  )     ?     1     :     left  [  i       j     -     1  ]     +     1  ;      top  [  i       j  ]     =     (  i     ==     0  )     ?     1     :     top  [  i     -     1       j  ]     +     1  ;      }      }      }          // Fill right and bottom matrices      for     (  int     i     =     n     -     1  ;     i     >=     0  ;     i  --  )     {      for     (  int     j     =     n     -     1  ;     j     >=     0  ;     j  --  )     {      if     (  mat  [  i       j  ]     ==     1  )     {      right  [  i       j  ]     =     (  j     ==     n     -     1  )     ?     1     :     right  [  i       j     +     1  ]     +     1  ;      bottom  [  i       j  ]     =     (  i     ==     n     -     1  )     ?     1     :     bottom  [  i     +     1       j  ]     +     1  ;      }      }      }          int     maxPlusSize     =     0  ;          // Compute the maximum '+' size      for     (  int     i     =     0  ;     i      <     n  ;     i  ++  )     {      for     (  int     j     =     0  ;     j      <     n  ;     j  ++  )     {      if     (  mat  [  i       j  ]     ==     1  )     {      int     armLength     =     Math  .  Min  (  Math  .  Min  (  left  [  i       j  ]     right  [  i       j  ])      Math  .  Min  (  top  [  i       j  ]     bottom  [  i       j  ]));          maxPlusSize     =     Math  .  Max  (  maxPlusSize        (  4     *     (  armLength     -     1  ))     +     1  );      }      }      }          return     maxPlusSize  ;      }      public     static     void     Main  ()     {          // Hardcoded input matrix      int  []     mat     =     {      {  0       1       1       0       1  }      {  0       0       1       1       1  }      {  1       1       1       1       1  }      {  1       1       1       0       1  }      {  0       1       1       1       0  }      };          Console  .  WriteLine  (  FindLargestPlus  (  mat  ));      }   }   
JavaScript
   // JavaScript program to find the largest '+' in a binary matrix   // using Dynamic Programming   function     findLargestPlus  (  mat  )     {          let     n     =     mat  .  length  ;          let     left     =     Array  .  from  ({     length  :     n     }     ()     =>     Array  (  n  ).  fill  (  0  ));      let     right     =     Array  .  from  ({     length  :     n     }     ()     =>     Array  (  n  ).  fill  (  0  ));      let     top     =     Array  .  from  ({     length  :     n     }     ()     =>     Array  (  n  ).  fill  (  0  ));      let     bottom     =     Array  .  from  ({     length  :     n     }     ()     =>     Array  (  n  ).  fill  (  0  ));          // Fill left and top matrices      for     (  let     i     =     0  ;     i      <     n  ;     i  ++  )     {      for     (  let     j     =     0  ;     j      <     n  ;     j  ++  )     {      if     (  mat  [  i  ][  j  ]     ===     1  )     {      left  [  i  ][  j  ]     =     (  j     ===     0  )     ?     1     :     left  [  i  ][  j     -     1  ]     +     1  ;      top  [  i  ][  j  ]     =     (  i     ===     0  )     ?     1     :     top  [  i     -     1  ][  j  ]     +     1  ;      }      }      }          // Fill right and bottom matrices      for     (  let     i     =     n     -     1  ;     i     >=     0  ;     i  --  )     {      for     (  let     j     =     n     -     1  ;     j     >=     0  ;     j  --  )     {      if     (  mat  [  i  ][  j  ]     ===     1  )     {      right  [  i  ][  j  ]     =     (  j     ===     n     -     1  )     ?     1     :     right  [  i  ][  j     +     1  ]     +     1  ;      bottom  [  i  ][  j  ]     =     (  i     ===     n     -     1  )     ?     1     :     bottom  [  i     +     1  ][  j  ]     +     1  ;      }      }      }          let     maxPlusSize     =     0  ;          // Compute the maximum '+' size      for     (  let     i     =     0  ;     i      <     n  ;     i  ++  )     {      for     (  let     j     =     0  ;     j      <     n  ;     j  ++  )     {      if     (  mat  [  i  ][  j  ]     ===     1  )     {      let     armLength     =     Math  .  min  (  left  [  i  ][  j  ]     right  [  i  ][  j  ]      top  [  i  ][  j  ]     bottom  [  i  ][  j  ]);          maxPlusSize     =     Math  .  max  (  maxPlusSize        (  4     *     (  armLength     -     1  ))     +     1  );      }      }      }          return     maxPlusSize  ;   }   // Hardcoded input matrix   let     mat     =     [      [  0       1       1       0       1  ]      [  0       0       1       1       1  ]      [  1       1       1       1       1  ]      [  1       1       1       0       1  ]      [  0       1       1       1       0  ]   ];   console  .  log  (  findLargestPlus  (  mat  ));   

Producción
9  

Complejidad temporal: O(n²) debido a cuatro pasadas para calcular las matrices direccionales y una pasada final para determinar el '+' más grande. Cada paso toma O(n²) tiempo, lo que lleva a una complejidad general de O(n²).
Complejidad espacial: O (n²) debido a que cuatro matrices auxiliares (izquierda, derecha, arriba, abajo) consumen O (n²) espacio adicional.