forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrumbs22.cpp
More file actions
57 lines (49 loc) ยท 1.45 KB
/
crumbs22.cpp
File metadata and controls
57 lines (49 loc) ยท 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
valid tree ์กฐ๊ฑด
1. ์ฌ์ดํด์ด ์์ด์ผํ๋ค
2. ๋ชจ๋ ๊ฐ ๋
ธ๋๋ค์ ์ ์ด๋ ํ๋์ ๋ค๋ฅธ ๋
ธ๋์ ์ฐ๊ฒฐ๋์ด ์์ด์ผ ํ๋ค
์ธ์ ๋ฆฌ์คํธ ํ์์ผ๋ก ๋ฌด๋ฐฉํฅ ๊ฐ์ ์ ๋ณด๋ฅผ ์ ์ฅํ๊ณ ,
dfs ์ฌ๊ท ํ์์ผ๋ก ๋ฐฉ๋ฌธ ์ฒดํฌ ํ ์์ ๋
ธ๋๋ฅผ ์ฌ๊ท์ ์ผ๋ก ๋ฐฉ๋ฌธํ๋ฉด์ ์ฌ์ดํด ํ๋จ
*/
class Solution {
public:
/**
* @param n: An integer
* @param edges: a list of undirected edges
* @return: true if it's a valid tree, or false
*/
bool validTree(int n, vector<vector<int>> &edges) {
if (edges.size() != n - 1)
return false;
// ์ธ์ ํ ๋
ธ๋๋ค์ ์์๋ก ๊ฐ์ง๋ adj ๋ฐฐ์ด ์์ฑ
vector<vector<int>> adj(n);
for (auto edge : edges) {
int u = edge[0];
int v = edge[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
// ๋ฐฉ๋ฌธ ๊ธฐ๋ก
vector<bool> visited(n, false);
if (!dfs(0, -1, adj, visited))
return false;
// ๋ชจ๋ ๋
ธ๋๊ฐ ๋ฐฉ๋ฌธ๋์๋์ง (์ฐ๊ฒฐ๋๋์ง) ํ์ธ
for (bool v : visited) {
if (!v)
return false;
}
return true;
}
bool dfs(int node, int parent, vector<vector<int>>& adj, vector<bool> visited) {
visited[node] = true;
for (int neighbor : adj[node]) {
if (neighbor == parent)
continue ; // ๋ฐ๋ก ์ด์ ๋
ธ๋๋ ๋ฌด์(์๋ณต ๋ฐฉ์ง)
if (visited[neighbor])
return false; // ์ฌ์ดํด ํ์ง
if (!dfs(neighbor, node, adj, visited))
return false;
}
return true;
}
};