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 |