Skip to content

Commit 5cd96ba

Browse files
author
Kohei Asai
authored
547. Friend Circles (axross#139)
1 parent 179b6b7 commit 5cd96ba

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

Diff for: solutions/friend_circles.ts

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// 547. Friend Circles
2+
// https://leetcode.com/problems/friend-circles/
3+
export default function findCircleNum(relationships: number[][]): number {
4+
const friendCircles: Set<number>[] = [];
5+
const visited = new Set<number>();
6+
7+
function traverse(person: number, friendCircle: Set<number>) {
8+
if (visited.has(person)) return;
9+
10+
friendCircle.add(person);
11+
visited.add(person);
12+
13+
for (const [other, isFriend] of relationships[person].entries()) {
14+
if (isFriend !== 1) continue;
15+
16+
traverse(other, friendCircle);
17+
}
18+
}
19+
20+
for (const person of relationships.keys()) {
21+
if (visited.has(person)) continue;
22+
23+
friendCircles.push(new Set());
24+
25+
traverse(person, friendCircles[friendCircles.length - 1]);
26+
}
27+
28+
return friendCircles.length;
29+
}

Diff for: solutions/friend_circles_test.ts

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { test } from "https://deno.land/std/testing/mod.ts";
2+
import { assertStrictEq } from "https://deno.land/std/testing/asserts.ts";
3+
import findCircleNum from "./friend_circles.ts";
4+
5+
test("547. Friend Circles", () => {
6+
assertStrictEq(findCircleNum([[1, 1, 0], [1, 1, 0], [0, 0, 1]]), 2);
7+
assertStrictEq(findCircleNum([[1, 1, 0], [1, 1, 1], [0, 1, 1]]), 1);
8+
assertStrictEq(
9+
findCircleNum([
10+
[1, 0, 1, 0, 0],
11+
[0, 1, 0, 0, 1],
12+
[1, 0, 1, 0, 0],
13+
[0, 0, 0, 1, 1],
14+
[0, 1, 0, 1, 1]
15+
]),
16+
2
17+
);
18+
assertStrictEq(
19+
findCircleNum([[1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1], [1, 0, 1, 1]]),
20+
1
21+
);
22+
});

0 commit comments

Comments
 (0)