Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

11725번 트리의 부모 찾기 #5

Merged
merged 3 commits into from
Sep 4, 2022
Merged

11725번 트리의 부모 찾기 #5

merged 3 commits into from
Sep 4, 2022

Conversation

NamJwong
Copy link
Member

@NamJwong NamJwong commented Sep 4, 2022

문제

풀이 후기

트리가 자식 개수에 제한이 있는지 검색을 해봐도 헷갈려서 좀 찾아보고 풀었다.
트리는 자식 개수에 제한은 없다.

처음 시도한 방법이 틀려서 질문 검색란에서 힌트를 얻어서 풀었다.
고려하지 못한 케이스가 있었다.

다른 사람의 풀이와 비교

출처

const sol = (input) => {
  const N = +input[0];
  input = input.slice(1);
  const tree = Array.from({ length: N + 1 }, () => new Array());
  input.map((val) => {
    const [from, to] = val.split(" ").map(Number);
    tree[from].push(to);
    tree[to].push(from); // 무방향 트리이므로 A->B, B->A 정보를 모두 넣어준다.
  });

  let check = Array.from({ length: N + 1 }, () => 0);
  function bfs() {
    const queue = [];
    check[1] = 1;
    for (let next of tree[1]) { // next(child) 노드 값의 인덱스에 1(부모 노드)값을 넣어주고, 큐에 넣어준다.
      check[next] = 1;    
      queue.push(next);
    }
    while (queue.length) {
      const node = queue.shift();
      for (let next of tree[node]) { // 노드를 순회하면서, 방문한 노드라면 건너뛴다.
        if (check[next]) continue;
        check[next] = node; // 위와 같이 next 인덱스에는 node(부모 노드)값을 넣는다.
        queue.push(next);
      }
    }
  }
  bfs();

  check = check.slice(2);
  let result = "";
  check.map((v) => (result += `${v}\n`)); // 체크 배열의 2번 인덱스(2번 노드)부터 출력한다.
  return result;
};

// 백준에서 입력을 받는 코드
const input = [];
require("readline")
  .createInterface(process.stdin, process.stdout)
  .on("line", (line) => {
    input.push(line);
  })
  .on("close", () => {
    console.log(sol(input));
    process.exit();
  });
  • 인접 리스트 형태의 그래프를 만들 때 Map보다는 이렇게 2차원 배열을 활용하는 것이 나은 것 같다.
  • 나도 이렇게 shift 두 번 말고 slice를 할걸 그랬다.

@NamJwong NamJwong self-assigned this Sep 4, 2022
@NamJwong NamJwong merged commit a98d351 into main Sep 4, 2022
@NamJwong NamJwong deleted the algorithm/#3 branch September 4, 2022 15:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

11725번 트리의 부모 찾기
1 participant