Dado um n × n matriz binária juntamente com consistindo em 0s e 1s . Sua tarefa é encontrar o tamanho do maior '+' forma que pode ser formada usando apenas 1s .

UM '+' forma consiste em uma célula central com quatro braços que se estendem em todas as quatro direções ( para cima, para baixo, esquerda e direita ) enquanto permanece dentro dos limites da matriz. O tamanho de um '+' é definido como o número total de células formando-o incluindo o centro e todos os braços.
matriz vs lista de matrizes
A tarefa é devolver o tamanho máximo de qualquer válido '+' em juntamente com . Se não '+' pode ser formado retorno .
Exemplos:
Entrada: com = [ [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] ]
Saída: 9
Explicação: Um ‘+’ com comprimento de braço de 2 (2 células em cada direção + 1 centro) pode ser formado no centro do 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
Tamanho total = (2 × 4) + 1 = 9
Entrada: com = [ [0 1 1] [0 0 1] [1 1 1] ]
Saída: 1
Explicação: Um '+' com comprimento de braço de 0 (0 células em cada direção + 1 centro) pode ser formado com qualquer um dos 1's.Entrada: com = [ [0] ]
Saída:
Explicação: Não O sinal ‘+’ pode ser formado.
[Abordagem ingênua] - Considere cada ponto como centro - O (n ^ 4) Tempo e O (n ^ 4) Espaço
Percorra as células da matriz uma por uma. Considere cada ponto percorrido como centro de um positivo e encontre o tamanho do +. Para cada elemento, percorremos da esquerda para a direita, de baixo para cima. O pior caso nesta solução acontece quando temos todos 1s.
O ideia é manter quatro matrizes auxiliares esquerda[][] direita[][] superior[][] inferior[][] para armazenar 1’s consecutivos em todas as direções. Para cada célula (eu j) na matriz de entrada, armazenamos as informações abaixo nestes quatro matrizes -
- esquerda (eu j) armazena o número máximo de 1s consecutivos no esquerda da célula (i j) incluindo a célula (i j).
- certo (eu j) armazena o número máximo de 1s consecutivos no certo da célula (i j) incluindo a célula (i j).
- topo (eu j) armazena o número máximo de 1s consecutivos em principal da célula (i j) incluindo a célula (i j).
- inferior (eu j) armazena o número máximo de 1s consecutivos em fundo da célula (i j) incluindo a célula (i j).
Depois de calcular o valor para cada célula das matrizes acima, o maior'+' seria formado por uma célula da matriz de entrada que possui valor máximo considerando o mínimo de ( esquerda (i j) direita (i j) superior (i j) inferior (i j) )
Podemos usar Programação Dinâmica para calcular a quantidade total de 1s consecutivos em todas as direções:
se mat(i j) == 1
esquerda (i j) = esquerda (i j - 1) + 1quantos MB tem um GBsenão esquerda (i j) = 0
se mat(i j) == 1
topo(i j) = topo(i - 1 j) + 1;senão topo (i j) = 0;
se mat(i j) == 1
fundo(i j) = fundo(i + 1 j) + 1;senão inferior(i j) = 0;
string.formato java
se mat(i j) == 1
direita (i j) = direita (i j + 1) + 1;senão certo (i j) = 0;
Abaixo está a implementação da abordagem acima:
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));
Saída
9
Complexidade de tempo: O(n²) devido a quatro passagens para calcular as matrizes direcionais e uma passagem final para determinar o maior '+'. Cada passagem leva tempo O(n²), levando a uma complexidade geral de O(n²).
Complexidade Espacial: O(n²) devido a quatro matrizes auxiliares (esquerda direita superior inferior) consumindo O (n²) espaço extra.