해커랭크(HackerRank)

Diagonal Difference

cepiloth 2018. 8. 19. 17:46
반응형


1. 문제

2차원 배열요소에서 각 대각 선의 합을 구하여 두 대각선의 차이의 절대 값을 구하는 문제.


2. 알고리즘

키워드 - 구현


3. 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <bits/stdc++.h>
 
using namespace std;
 
/*
 * Complete the diagonalDifference function below.
 */
int diagonalDifference(vector<vector<int>> a) {
    /*
     * Write your code here.
     */
    
    int row = a.size();
    int colum = a[0].size();
    
    int xAxis = 0;
    for(int i = ; i < row; i ++) {
        xAxis += a[i][i];
    }
    
    int yAxis = 0;
    for(int i = ; i < row; i ++) {
        yAxis += a[row-i-1][i];
    }
    
    
    return abs(xAxis - yAxis);
}
 
int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));
 
    int n;
    cin >> n;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
 
    vector<vector<int>> a(n);
    for (int a_row_itr = 0; a_row_itr < n; a_row_itr++) {
        a[a_row_itr].resize(n);
 
        for (int a_column_itr = 0; a_column_itr < n; a_column_itr++) {
            cin >> a[a_row_itr][a_column_itr];
        }
 
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
 
    int result = diagonalDifference(a);
 
    fout << result << "\n";
 
    fout.close();
 
    return 0;
}
cs

반응형