๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿš“ Self Study/๐Ÿ”“ LeetCode

LeetCode (Employee Importance) C++

by UKHYUN22 2022. 1. 6.
728x90

 

BFS๋กœ ์ ‘๊ทผํ•ด์„œ ํ‘ผ ๋ฌธ์ œ. ๋จธ๋ฆฟ ์†์— ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด ์žˆ๋‹ค๋ฉด ๋‚ด๊ฐ€ ํ•ญ์ƒ ํ’€๋˜ ๋ฐฉ์‹์ด ์•„๋‹ˆ๋ผ ์ฃผ์–ด์ง„ Structure๋กœ ํ’€ ์ˆ˜ ์žˆ์–ด์•ผ ํ–ˆ๋˜ ๋ฌธ์ œ์˜€๋‹ค. BFS๊ฐ€ ๊ฐ€๋ฌผ๊ฐ€๋ฌผ ํ•ด์ง€๋ฉด ๋ณด๋Ÿฌ์˜ค์Ÿˆ!

 

 

/*
// Definition for Employee.
class Employee {
public:
    int id;
    int importance;
    vector<int> subordinates;
};
*/

class Solution {
public:
    int getImportance(vector<Employee*> employees, int id) {
        int answer = 0;
        int index = 0;
        
        queue<int> q;
        q.push(id);
        
       while(!q.empty()) {
           int node = q.front();
           
           // id์— ํ•ด๋‹นํ•˜๋Š” ๊ฒƒ์ด ๋ช‡ ๋ฒˆ์งธ index ์ธ์ง€ ์ฐพ์„ ์ˆ˜ ์žˆ์Œ
            for(int i =0 ; i < employees.size() ; i++) {
                if(node == employees[i]->id) {
                    index = i;
                    break;
                }
            }
           answer += employees[index]->importance;           
           q.pop();
           
           if(employees[index]->subordinates.size() == 0) continue;
           
           for(int j =0 ; j < employees[index]->subordinates.size() ; j++) {
               q.push(employees[index]->subordinates[j]);
           }
       }
        
        return answer;
    }
};

 

'๐Ÿš“ Self Study > ๐Ÿ”“ LeetCode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode (Add two numbers) C++  (0) 2022.01.07
LeetCode (Two Sum) C++  (0) 2022.01.07
LeetCode (Sum of Left Leaves) C++  (0) 2022.01.06