|
| 1 | +/** |
| 2 | + * @param words: a list of words |
| 3 | + * @return: a string which is correct order |
| 4 | + */ |
| 5 | +const alienOrder = (words) => { |
| 6 | + const graph = {}; |
| 7 | + |
| 8 | + // ์ด๊ธฐํ |
| 9 | + for (const word of words) { |
| 10 | + for (const char of word) { |
| 11 | + if (!graph[char]) { |
| 12 | + graph[char] = new Set(); |
| 13 | + } |
| 14 | + } |
| 15 | + } |
| 16 | + |
| 17 | + // ๊ทธ๋ํ ์์ฑ |
| 18 | + for (let i = 1; i < words.length; i++) { |
| 19 | + const prev = words[i - 1]; |
| 20 | + const current = words[i]; |
| 21 | + let found = false; |
| 22 | + |
| 23 | + const minLen = Math.min(prev.length, current.length); |
| 24 | + for (let j = 0; j < minLen; j++) { |
| 25 | + graph[prev[j]].add(current[j]); |
| 26 | + } |
| 27 | + // ๋ชจ์ ์ฒ๋ฆฌ |
| 28 | + if (!found && prev.length > current.length) { |
| 29 | + return ''; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + // ํ์ |
| 34 | + const output = []; |
| 35 | + const visiting = new Set(); |
| 36 | + const visited = new Set(); |
| 37 | + |
| 38 | + function dfs(current) { |
| 39 | + if (visiting.has(current)) { |
| 40 | + return false; |
| 41 | + } |
| 42 | + if (visited.has(current)) { |
| 43 | + return true; |
| 44 | + } |
| 45 | + |
| 46 | + visiting.add(current); |
| 47 | + for (const adj of graph[current]) { |
| 48 | + if (!dfs(adj)) { |
| 49 | + return false; |
| 50 | + } |
| 51 | + } |
| 52 | + visiting.delete(current); |
| 53 | + |
| 54 | + visited.add(current); |
| 55 | + output.push(current); |
| 56 | + return true; |
| 57 | + } |
| 58 | + |
| 59 | + // ์ํ |
| 60 | + for (const node in graph) { |
| 61 | + if (!dfs(node)) { |
| 62 | + return ''; |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + return output.reverse().join('') |
| 67 | +} |
| 68 | + |
| 69 | + |
| 70 | +// ๋ฐฉํฅ ๊ทธ๋ํ๋ก ์ ํ๋๋ ์์๋ฅผ ํํ |
| 71 | +// ๋น์ทํ ๋ฌธ์ : https://leetcode.com/problems/course-schedule/description/ |
| 72 | + |
| 73 | +// ์์์ ๋ ฌ ์ฌ์ฉํด์ ์ง์
์ฐจ์ ๊ธฐ์ค ์ ๋ ฌํ๋ ๋ฐฉ๋ฒ๋ ์์ |
| 74 | +// ๋๋ฌด ์ด๋ ค์ ๋ค... |
0 commit comments