File tree Expand file tree Collapse file tree 2 files changed +64
-0
lines changed
number-of-connected-components-in-an-undirected-graph Expand file tree Collapse file tree 2 files changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+ // V๋ ์ ์ , E๋ ๊ฐ์
2+ // ์๊ฐ ๋ณต์ก๋: O(V + E)
3+ // ๊ณต๊ฐ ๋ณต์ก๋: O(V + E)
4+
5+ class Solution {
6+ /**
7+ * @param {number } n
8+ * @param {number[][] } edges
9+ * @returns {number }
10+ */
11+ countComponents ( n , edges ) {
12+ const visited = Array . from ( { length : n } , ( ) => false ) ;
13+ const graph = new Map ( ) ;
14+
15+ for ( const [ v , d ] of edges ) {
16+ if ( ! graph . has ( v ) ) graph . set ( v , [ ] ) ;
17+ if ( ! graph . has ( d ) ) graph . set ( d , [ ] ) ;
18+
19+ graph . get ( v ) . push ( d ) ;
20+ graph . get ( d ) . push ( v ) ;
21+ }
22+
23+ const dfs = ( node ) => {
24+ visited [ node ] = true
25+ for ( let nei of graph . get ( node ) || [ ] ) {
26+ if ( ! visited [ nei ] ) dfs ( nei )
27+ }
28+ }
29+
30+ let count = 0 ;
31+ for ( let i = 0 ; i < n ; i ++ ) {
32+ if ( ! visited [ i ] ) {
33+ dfs ( i ) ;
34+ count ++ ;
35+ }
36+ }
37+
38+
39+ return count
40+ }
41+ }
Original file line number Diff line number Diff line change 1+ // ์๊ฐ๋ณต์ก๋: O(n)
2+ // ๊ณต๊ฐ๋ณต์ก๋: O(n)
3+
4+ /**
5+ * Definition for a binary tree node.
6+ * function TreeNode(val, left, right) {
7+ * this.val = (val===undefined ? 0 : val)
8+ * this.left = (left===undefined ? null : left)
9+ * this.right = (right===undefined ? null : right)
10+ * }
11+ */
12+ /**
13+ * @param {TreeNode } p
14+ * @param {TreeNode } q
15+ * @return {boolean }
16+ */
17+ var isSameTree = function ( p , q ) {
18+ if ( ( p && ! q ) || ( ! p && q ) ) return false ;
19+ if ( ! p || ! q ) return true
20+ if ( p . val === q . val ) return isSameTree ( p . left , q . left ) && isSameTree ( p . right , q . right )
21+ return false
22+ } ;
23+
You canโt perform that action at this time.
0 commit comments