Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Complete the surfaceArea function below.
- static int surfaceArea(int[][] A) {
- int surface = A.length * A[0].length * 2;
- for (int i = 0; i < A.length; i++) {
- for (int j = 0; j < A[i].length; j++) {
- // check top
- int topNeighbour = i == 0 ? 0 : A[i-1][j];
- int diff = A[i][j] - topNeighbour;
- if (diff > 0) {
- surface += diff;
- }
- // check bottom
- int bottomNeighbour = i == A.length - 1 ? 0 : A[i + 1][j];
- diff = A[i][j] - bottomNeighbour;
- if (diff > 0) {
- surface += diff;
- }
- // check left
- int leftNeighbour = j == 0 ? 0 : A[i][j - 1];
- diff = A[i][j] - leftNeighbour;
- if (diff > 0) {
- surface += diff;
- }
- // check right
- int rightNeighbour = j == A[i].length - 1 ? 0 : A[i][j + 1];
- diff = A[i][j] - rightNeighbour;
- if (diff > 0) {
- surface += diff;
- }
- }
- }
- return surface;
- }
Advertisement
Add Comment
Please, Sign In to add comment