C++, test in 4 directions + prefix sums
\n//firstly count \'5\' s and \'2\' s for every cell,  (each pair of (5,2) will generate a trailing zero),\n//use prefix sums to accelerate the counting of 5s a
```\n//firstly count \'5\' s and \'2\' s for every cell,  (each pair of (5,2) will generate a trailing zero),\n//use prefix sums to accelerate the counting of 5s and 2s.\n//and then check in 4 directions to find out the turn has max count of pairs (5,2)\nclass Solution {\npublic:\n\tint maxTrailingZeros(vector<vector<int>>& grid) {\n\t\tint m = grid.size(), n = grid[0].size(), r = 0, i, j, v, fiveCount, twoCount, a, b, a1, b1, a2, b2, a3, b3, a4, b4;\n\t\tvector<vector<int>> fiveHor(m, vector<int>(n, 0)), fiveVer(m, vector<int>(n, 0)),twoHor(m, vector<int>(n, 0)),  twoVer(m, vector<int>(n, 0));\n\n\t\tfor (i = 0; i < m; ++i) {\n\t\t\tfor (j = 0; j < n; ++j) {\n\t\t\t\tv = grid[i][j], fiveCount = 0, twoCount = 0;\n\t\t\t\twhile (v % 5 == 0) { fiveCount++;  v /= 5; }\n\t\t\t\twhile (v && (v % 2 == 0)) { twoCount++; v /= 2; }\n\n\t\t\t\tfiveHor[i][j] = ((j == 0) ? 0 : fiveHor[i][j - 1]) + fiveCount;   //five prefix sum in horizontal\n\t\t\t\tfiveVer[i][j] = ((i == 0) ? 0 : fiveVer[i - 1][j]) + fiveCount;   //five prefix sum in vertical\n                \n\t\t\t\ttwoHor[i][j]  = ((j == 0) ? 0 : twoHor[i][j - 1]) + twoCount;     //two prefix sum in horizontal\t\t\t\t\n                twoVer[i][j]  = ((i == 0) ? 0 : twoVer[i - 1][j]) + twoCount;     //two prefix sum in vertical\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0; i < m; ++i) {\n\t\t\tfor (j = 0; j < n; ++j) {\n\t\t\t\ta = fiveHor[i][j] - (j == 0 ? 0 : fiveHor[i][j - 1]); //current cell\'s count of 5\n\t\t\t\tb = twoHor[i][j]  - (j == 0 ? 0 : twoHor[i][j - 1]); //current cell\'s count of 2\n                \n\t\t\t\ta1 = fiveHor[i][n - 1] - fiveHor[i][j];                b1 = twoHor[i][n - 1] - twoHor[i][j];    //right\n\t\t\t\ta2 = fiveVer[m - 1][j] - fiveVer[i][j];                b2 = twoVer[m - 1][j] - twoVer[i][j];    //down\n\t\t\t\ta3 = (j == 0) ? 0 : fiveHor[i][j - 1];                 b3 = (j == 0) ? 0 : twoHor[i][j - 1];    //left\n\t\t\t\ta4 = (i == 0) ? 0 : fiveVer[i - 1][j];                 b4 = (i == 0) ? 0 : twoVer[i - 1][j];    //up\n\n\t\t\t\tr = max(r, min(a + a1 + a2, b + b1 + b2));\n\t\t\t\tr = max(r, min(a + a2 + a3, b + b2 + b3));\n\t\t\t\tr = max(r, min(a + a3 + a4, b + b3 + b4));\n\t\t\t\tr = max(r, min(a + a4 + a1, b + b4 + b1));\n\t\t\t}\n\t\t}\n\n\t\treturn r;\n\t}\n};\n```
[]