File tree Expand file tree Collapse file tree 1 file changed +6
-12
lines changed
number-of-connected-components-in-an-undirected-graph Expand file tree Collapse file tree 1 file changed +6
-12
lines changed Original file line number Diff line number Diff line change 55Big O
66- N: ๋
ธ๋ ๊ฐ์
77- E: ๊ฐ์ ์ ๊ฐ์
8- - Time complexity: O(N)
9- - ์ ์ฒด ๋
ธ๋๋ฅผ ์ต๋ 1๋ฒ์ฉ ์กฐํํฉ๋๋ค
8+ - Time complexity: O(N + E)
9+ - adj๋ฅผ ์์ฑํ๋ ๋ฐ๋ณต๋ฌธ์ ์๊ฐ๋ณต์ก๋๋ E์ ๋น๋กํ์ฌ ์ฆ๊ฐํฉ๋๋ค
10+ - ์ ์ฒด ๋
ธ๋๋ฅผ ์ต๋ 1๋ฒ์ฉ ์กฐํํ๋ฏ๋ก ๋๋ฒ์งธ ๋ฐ๋ณต๋ฌธ์ ์๊ฐ๋ณต์ก๋๋ N์ ๋น๋กํ์ฌ ์ฆ๊ฐํฉ๋๋ค
1011- Space complexity: O(N + E)
1112 - adjacency list์ ํฌ๊ธฐ๋ E์ ๋น๋กํ์ฌ ์ฆ๊ฐํฉ๋๋ค
12- - ๋ set์ ํฌ๊ธฐ๋ N์ ๋น๋กํ์ฌ ์ฆ๊ฐํฉ๋๋ค
13+ - checked์ ํฌ๊ธฐ๋ N์ ๋น๋กํ์ฌ ์ฆ๊ฐํฉ๋๋ค
1314 - check ํจ์์ ์ฌ๊ท ํธ์ถ ์คํ ๊น์ด ๋ํ ์ต์
์ ๊ฒฝ์ฐ, N์ ๋น๋กํ์ฌ ์ฆ๊ฐํฉ๋๋ค
1415*/
1516
@@ -20,24 +21,17 @@ func countComponents(n int, edges [][]int) int {
2021 adj [edge [1 ]] = append (adj [edge [1 ]], edge [0 ])
2122 }
2223 // Go๋ {int: bool} hashmap์ set์ฒ๋ผ ์ฌ์ฉํจ
23- checking := make (map [int ]bool ) // ํ์ฌ ์งํ์ค์ธ DFS ํ์์์ ๋ฐฉ๋ฌธํ ๋
ธ๋๋ฅผ ๊ธฐ๋กํจ
2424 checked := make (map [int ]bool ) // ๋ชจ๋ ํ์์ด ๋๋ ๋
ธ๋๋ฅผ ๊ธฐ๋กํจ
2525 // ๊ฐ node๋ฅผ ์กฐํํ๋ ํจ์
2626 var check func (int )
2727 check = func (i int ) {
28- // ์ด๋ฏธ ๋ฐฉ๋ฌธํ ์ ์ด ์๋ node๋ผ๋ฉด ํ์ํ ํ์๊ฐ ์์
29- if _ , ok := checked [i ]; ok {
30- return
31- }
32- checking [i ] = true
28+ checked [i ] = true
3329 for _ , nxt := range adj [i ] {
34- if _ , ok := checking [nxt ]; ok {
30+ if _ , ok := checked [nxt ]; ok {
3531 continue
3632 }
3733 check (nxt )
3834 }
39- delete (checking , i )
40- checked [i ] = true
4135 }
4236
4337 res := 0
You canโt perform that action at this time.
0 commit comments