Submission
Status:
PPPPPPPPPP
Score: 100
User: admin
Problemset: บริษัททำความสะอาด
Language: cpp
Time: 0.002 second
Submitted On: 2024-11-25 14:39:24
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
class Solution {
public:
int surfaceArea(vector<vector<int>>& grid) {
int n = grid.size(); // Grid size
int totalSurfaceArea = 0; // To store the total surface area
// Iterate over each cell in the grid
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] > 0) {
// Count the top and bottom surfaces
totalSurfaceArea += 2;
// Count the four sides
// North side
totalSurfaceArea += (i == 0) ? grid[i][j] : max(0, grid[i][j] - grid[i - 1][j]);
// South side
totalSurfaceArea += (i == n - 1) ? grid[i][j] : max(0, grid[i][j] - grid[i + 1][j]);
// West side
totalSurfaceArea += (j == 0) ? grid[i][j] : max(0, grid[i][j] - grid[i][j - 1]);
// East side
totalSurfaceArea += (j == n - 1) ? grid[i][j] : max(0, grid[i][j] - grid[i][j + 1]);
}
}
}
return totalSurfaceArea;
}
};
// Function to parse input in the desired format
vector<vector<int>> readInput(int n, const string& input) {
vector<vector<int>> grid(n, vector<int>(n));
stringstream ss(input);
char ch;
int num;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
// Skip non-numeric characters
while (ss >> ch && !isdigit(ch)) {}
ss.putback(ch); // Put the digit back to read it as an integer
ss >> num; // Read the actual number
grid[i][j] = num;
}
}
return grid;
}
int main() {
int n;
string input;
// Read the grid size
cin >> n;
cin.ignore(); // Ignore the newline character
// Read the input grid as a string
getline(cin, input);
// Parse the input string to get the grid
vector<vector<int>> grid = readInput(n, input);
Solution solution;
int result = solution.surfaceArea(grid); // Calculate surface area
cout << result << endl; // Output the result
return 0;
}