본문 바로가기

Algorithm/Code Fights (Code Signal)

Aracade Intro #8 MatrixElementsSum

 Each cell in the matrix contains an integer that represents the price of them. Some rooms are free(0), because they are haunted. They are not suitable to live in.

Calculate the total price of all the rooms that are suitable to live in.


 입력받은 2차원 배열(월세 가격)에서 0 인 위치는 귀신이 있는 집이다.

가격이 0인 위치와 0의 바로 아랫줄(같은 열) 은 어디든 살기 싫다. 

살 수 있는 적합한 방의 배열위치에 있는 모든 가격(정수)의 합을 구하라.


e.g. 

matrix = [[ 1, 3, 4, 0 ],

 [ 3, 0, 6, 10],

 [ 0, 2, 0, 0],

 [ 2, 3, 4, 1]];


[ 1, 3, 4, x ],

[ 3, x, 6, x ],

[ x, x, x, x ],

[ x, x, x, x ]


1 + 3 + 4 + 3 + 6 = 17


matrixElementsSum(matrix) = 17


//Process

//1. Input 2D vector (room fee)

//2. Make hauntedColumnNumber to check it's haunted col or not

//3. Iterate row

// 3.1. Iterate col

//  3.1.1. Check if it's on below haunted column

//  3.1.2. If not -> add to sum 

//4. Return sum


//처리과정

//1. 2차원 배열 입력받는다 (방 가격)

//2. 해당 컬럼이 귀신든 열인지 확인한다.

//3. 행을 반복한다.

// 3.1. 열을 반복한다.

//  3.1.1. 귀신든 열에 속하는지 확인해서

//  3.1.2. 아니면 합에 더한다.


int matrixElementsSum(std::vector<std::vector<int>> matrix) {


    int sum = 0;

    

    std::vector<int> hauntedColumnNumber(matrix[0].size(), 0);

    

    for (int i = 0; i < matrix.size(); ++i)

    {

        for (int j = 0; j < matrix[i].size(); ++j) 

        {

            if (hauntedColumnNumber[j] != 1 && matrix[i][j] != 0) 

            {

                sum += matrix[i][j];

            }

            else 

            {

                hauntedColumnNumber[j] = 1;

            }

        }

    }

    return sum;

}



2018/09/24 - [Algorithm/Code Signal (Code Fights)] - Aracade Intro #8 MatrixElementsSum

2018/09/23 - [Algorithm/Code Signal (Code Fights)] - Aracade Intro #7 AlmostIncreasingSequence

2018/09/22 - [Algorithm/Code Signal (Code Fights)] - Aracade Intro #6 MakeArrayConsecutive2

2018/09/21 - [Algorithm/Code Signal (Code Fights)] - Aracade Intro #5 ShapeArea

2018/09/19 - [Algorithm/Code Signal (Code Fights)] - Aracade Intro #4 AdjacentElementsProduct

2018/09/16 - [Algorithm/Code Signal (Code Fights)] - Aracade Intro #3 CheckPalindrome

2018/09/16 - [Algorithm/Code Signal (Code Fights)] - Aracade Intro #2 CenturyFromYear

2018/09/16 - [Algorithm/Code Signal (Code Fights)] - Aracade Intro #1 Add