Pacman And Numbers- Editorial || PACNUM

PROBLEM LINK: Pacman And Numbers | CodeChef

Problem Code: Pacman And Numbers | CodeChef

Practice: Pacman And Numbers | CodeChef

Contest: Campus Code October Edition, test page Coding Competition | CodeChef

Author: Codechef Adgitm Chapter : https://www.codechef.com/users/test_account_9
Tester: Codechef Adgitm Chapter : https://www.codechef.com/users/test_account_9
Editorialist: Codechef Adgitm Chapter : https://www.codechef.com/users/test_account_9

DIFFICULTY:

MEDIUM

PROBLEM:

Pacman and his girlfriend Pacwoman love to eat numbers. They were out walking when they found a square park with numbers laying around in the form of a square matrix of size n x n. Pacman and pacwoman mutually decide to eat all the numbers at the perimeter of the square alternatively. So first, pacman eats all the numbers at the perimeter, then pacwoman eats all the numbers in the perimeter of the remaining square and then pacman and so on. Find the sum of all the numbers that pacman ate.

SOLUTION:

C++:
#include <bits/stdc++.h>
#define int long long int
using namespace std;

int sumPerimeter(vector<vector> &arr, int d) {
int sum = 0;
int n = arr.size();
for (int i = d; i < n - d; i++) {
sum += arr[d][i];
if (n - 1 - d != d)
sum += arr[n - 1 - d][i];
}
for (int i = d + 1; i < n - d - 1; i++) {
sum += arr[i][d];
if (n - 1 - d != d)
sum += arr[i][n - 1 - d];
}
return sum;
}

int32_t main() {
int t;
cin >> t;
while (t–) {
int n;
cin >> n;
vector<vector> arr(n, vector(n));
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> arr[i][j];

    int ans = 0;
    for (int i = 0; i < (n + 1) / 2; i += 2) {
        ans += sumPerimeter(arr, i);
    }

    cout << ans << endl;
}

// fin.close();
// fout.close();
return 0;

}