Douma37

3D surface

Aug 14th, 2019
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1.     // Complete the surfaceArea function below.
  2.     static int surfaceArea(int[][] A) {
  3.         int surface = A.length * A[0].length * 2;
  4.         for (int i = 0; i < A.length; i++) {
  5.             for (int j = 0; j < A[i].length; j++) {
  6.                 // check top
  7.                 int topNeighbour = i == 0 ? 0 : A[i-1][j];
  8.                 int diff = A[i][j] - topNeighbour;
  9.                 if (diff > 0) {
  10.                     surface += diff;
  11.                 }
  12.  
  13.                 // check bottom
  14.                 int bottomNeighbour = i == A.length - 1 ? 0 : A[i + 1][j];
  15.                 diff = A[i][j] - bottomNeighbour;
  16.                 if (diff > 0) {
  17.                     surface += diff;
  18.                 }
  19.  
  20.                 // check left
  21.                 int leftNeighbour = j == 0 ? 0 : A[i][j - 1];
  22.                 diff = A[i][j] - leftNeighbour;
  23.                 if (diff > 0) {
  24.                     surface += diff;
  25.                 }
  26.  
  27.                 // check right
  28.                 int rightNeighbour = j == A[i].length - 1 ? 0 : A[i][j + 1];
  29.                 diff = A[i][j] - rightNeighbour;
  30.                 if (diff > 0) {
  31.                     surface += diff;
  32.                 }
  33.             }
  34.         }
  35.         return surface;
  36.     }
Advertisement
Add Comment
Please, Sign In to add comment