LeetCode 2245: Maximum Trailing Zeros in a Cornered Path
Problem Description
Explanation
To solve this problem, we can iterate through all possible cornered paths in the grid and calculate the product of each path. For each product, we count the number of trailing zeros. To find the maximum number of trailing zeros in any cornered path, we keep track of the maximum trailing zeros found so far.
We can start by defining a function to calculate the number of trailing zeros in a given number. Then, we can implement a function to explore all possible cornered paths in the grid and update the maximum trailing zeros. To avoid revisiting cells, we can maintain a boolean visited array.
The overall time complexity of this approach is O(mn) where m and n are the dimensions of the grid, as we need to explore all possible paths. The space complexity is also O(mn) to store the visited array.
Solutions
class Solution {
public int maxTrailingZeros(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[] maxZeros = new int[1];
boolean[][] visited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
dfs(grid, i, j, 0, 0, maxZeros, visited);
}
}
return maxZeros[0];
}
private void dfs(int[][] grid, int i, int j, int zeros, int product, int[] maxZeros, boolean[][] visited) {
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || visited[i][j]) {
return;
}
int num = grid[i][j];
product *= num;
while (num % 10 == 0) {
zeros++;
num /= 10;
}
visited[i][j] = true;
maxZeros[0] = Math.max(maxZeros[0], zeros);
dfs(grid, i + 1, j, zeros, product, maxZeros, visited);
dfs(grid, i - 1, j, zeros, product, maxZeros, visited);
dfs(grid, i, j + 1, zeros, product, maxZeros, visited);
dfs(grid, i, j - 1, zeros, product, maxZeros, visited);
visited[i][j] = false;
}
}
Loading editor...