Skip to content

Instantly share code, notes, and snippets.

@adil1214
Last active November 21, 2017 21:24
Show Gist options
  • Save adil1214/64eba65e4ba6e3074bcc11ebfa5a6ccd to your computer and use it in GitHub Desktop.
Save adil1214/64eba65e4ba6e3074bcc11ebfa5a6ccd to your computer and use it in GitHub Desktop.
/*input
3 3
1 3 4
2 2 3
1 2 4
*/
// expected output is 60
#include <bits/stdc++.h>
using namespace std;
long surfaceArea(const vector< vector<int> > & a) {
int rows , cols;
long count=0;
rows = a.size();
cols = a[0].size();
if ( rows == 0 || cols == 0 ) {
return 0;
} else if ( rows == 1 && cols == 1 ) {
count = 2 + (a[0][0]*4);
} else if ( rows == 1 ) {
for (int i = 0; i < cols-1; ++i) {
count += abs(a[0][i]-a[0][i+1]);
count += a[0][i]*2;
// count += 2;
}
count += a[0][0];
count += a[0][cols-1]*3;
count += 2*cols;
} else if ( cols == 1 ) {
for (int i = 0; i < rows-1; ++i) {
count += abs(a[i][0]-a[i+1][0]);
count += a[i][0]*2;
//count += 2;
}
count += a[0][0];
count += a[rows-1][0]*3;
count += 2*rows;
} else {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if ( i != rows-1 ) {
count += abs( a[i][j] - a[i+1][j] );
}
if ( j != cols-1 ) {
count += abs( a[i][j] - a[i][j+1] );
}
if ( i==0 || j==0 || i == rows-1 || j == cols-1 ) {
count += a[i][j];
if ( i==j || i==cols-1-j || j==rows-1-i )
count += a[i][j];
}
}
}
count += 2*rows*cols;
}
return count;
}
int main()
{
int H;
int W;
cin >> H >> W;
vector< vector<int> > A(H,vector<int>(W));
for(int A_i = 0;A_i < H;A_i++){
for(int A_j = 0;A_j < W;A_j++){
cin >> A[A_i][A_j];
}
}
long result = surfaceArea(A);
cout << result << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment