|
| 1 | +function isPossible(n: number, edges: number[][]): boolean { |
| 2 | + const s = new Set<string>(); |
| 3 | + |
| 4 | + const deg = new Map<number, number>(); |
| 5 | + |
| 6 | + for (const [x, y] of edges) { |
| 7 | + s.add(JSON.stringify([x, y])); |
| 8 | + s.add(JSON.stringify([y, x])); |
| 9 | + |
| 10 | + deg.set(x, (deg.get(x) ?? 0) + 1); |
| 11 | + deg.set(y, (deg.get(y) ?? 0) + 1); |
| 12 | + } |
| 13 | + |
| 14 | + const odd = [...deg].filter(([_, d]) => d % 2 > 0).map((a) => a[0]); |
| 15 | + |
| 16 | + const m = odd.length; |
| 17 | + |
| 18 | + if (m === 0) return true; |
| 19 | + |
| 20 | + if (m === 2) { |
| 21 | + const x = odd[0]; |
| 22 | + const y = odd[1]; |
| 23 | + |
| 24 | + if (!s.has(JSON.stringify([x, y]))) { |
| 25 | + return true; |
| 26 | + } |
| 27 | + for (let i = 1; i <= n; i++) { |
| 28 | + if ( |
| 29 | + i != x && |
| 30 | + i != y && |
| 31 | + !s.has(JSON.stringify([i, x])) && |
| 32 | + !s.has(JSON.stringify([i, y])) |
| 33 | + ) { |
| 34 | + return true; |
| 35 | + } |
| 36 | + } |
| 37 | + return false; |
| 38 | + } |
| 39 | + if (m == 4) { |
| 40 | + const [a, b, c, d] = odd; |
| 41 | + return !s.has(JSON.stringify([a, b])) && |
| 42 | + !s.has(JSON.stringify([c, d])) || |
| 43 | + !s.has(JSON.stringify([a, c])) && !s.has(JSON.stringify([b, d])) || |
| 44 | + !s.has(JSON.stringify([a, d])) && !s.has(JSON.stringify([b, c])); |
| 45 | + } |
| 46 | + return false; |
| 47 | +} |
| 48 | +export default isPossible; |
0 commit comments