給定一個正整數 k,你需要建立一個大小為 k×k 的矩陣,使得 1 到 k 的每個數字恰好出現一次。剩下的格子應該填入 0。
另外給定一個大小為 n 的二維整數陣列 rowConditions,其中 rowConditions[i]=[abovei,belowi],以及一個大小為 m 的二維整數陣列 colConditions,其中 colConditions[i]=[lefti,righti]。這兩個陣列的元素都是從 1 到 k 的整數。
classSolution: defbuildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]: deftopo_sort(conditions: List[List[int]]) -> List[int]: g = [[] for _ inrange(k)] # adjacency list deg = [0] * k # in-degree for x, y in conditions: # x 必須在 y 之前 g[x - 1].append(y - 1) deg[y - 1] += 1 order = [] # 拓樸排序的結果,第 i 個元素是 x q = deque(i for i, d inenumerate(deg) if d == 0) while q: x = q.popleft() order.append(x) for y in g[x]: deg[y] -= 1 if deg[y] == 0: q.append(y) pos = [0] * k # 把「第 i 個元素是 x」轉換為「x 在第 i 個位置」 for i, x inenumerate(order): pos[x] = i return pos iflen(order) == k else [] row, col = topo_sort(rowConditions), topo_sort(colConditions) ifnot row ornot col: return [] ans = [[0] * k for _ inrange(k)] for x, (i, j) inenumerate(zip(row, col)): # x 在第 i 橫列,第 j 直行 ans[i][j] = x + 1 return ans
classSolution { public: vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions) { vector<int> row, col; row = topological_sort(k, rowConditions); col = topological_sort(k, colConditions); if (row.empty() || col.empty()) return {}; vector<vector<int>> ans(k, vector<int>(k, 0)); for (int x = 0; x < k; x++) { // x 在第 i 橫列,第 j 直行 ans[row[x]][col[x]] = x + 1; } return ans; } vector<int> topological_sort(int k, vector<vector<int>>& conditions){ vector<vector<int>> g(k); // adjacency list vector<int> deg(k); // in-degree for (auto &e : conditions) { int x = e[0], y = e[1]; g[x - 1].push_back(y - 1); deg[y - 1]++; } vector<int> order; // 拓樸排序的結果,第 i 個元素是 x deque<int> q; for (int i = 0; i < k; i++) { if (deg[i] == 0) q.push_back(i); } while (!q.empty()) { int x = q.front(); q.pop_front(); order.push_back(x); for (int y : g[x]) { deg[y]--; if (deg[y] == 0) q.push_back(y); } } if (order.size() != k) return {}; vector<int> pos(k); // 把「第 i 個元素是 x」轉換為「x 在第 i 個位置」 for (int i = 0; i < k; i++) pos[order[i]] = i; return pos; } };
寫在最後
masterpiece, best quality, high quality, extremely detailed CG unity 8k wallpaper, extremely detailed, High Detail,
1 girl, solo, long hair, black hair, blue eyes, skirt, shirt, school uniform, standing, white shirt, short sleeves, pleated skirt, outdoors, sky, serafuku, (pink serafuku, pink school uniform), day, sailor collar, blurry, arm up, neckerchief, long skirt, girl