[問題] find vector內元素 卻完全沒作用
開發平台(Platform): Win11
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
Leetcode C++
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
non
問題(Question):
目前在寫Leetcode 的 133. Clone Graph
https://leetcode.com/problems/clone-graph/description/
(Node的結構是
int val;
vector<Node*> neighbors;)
我是用DFS方法跑每個點
用vector<int>記錄跑過點的數值(因為數值是唯一的不會重複)
但是 當我用find去看我有沒有記錄到這個數值
卻會發生明明有記錄到 iterator卻還是跑到vector.end() 造成不斷重複而TLE
用printf去印就發現一堆重複的數字被放入vector<int>
我知道可以用set 但是這個詭異的情況我想搞清楚到底是出了甚麼錯
錯誤結果(Wrong Output):
https://i.imgur.com/Vakk1Co.png

下面就是無線增長直到爆掉
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
void dfs(Node *ans, Node *ori, vector<int> *tfound)
{
int idx,temp;
printf("%d\n",ans->val);
tfound->push_back(ans->val);
for(int a : *tfound)
{
printf("found %d ", a);
}
printf("\n");
for(Node *n : ori->neighbors)
{
if(find(tfound->begin(), tfound->end(), n->val) == tfound->end())
{
Node *tn = new Node(n->val);
ans->neighbors.push_back(tn);
tn->neighbors.push_back(ans);
dfs(ans->neighbors[idx], ori->neighbors[idx], tfound);
}
}
return;
}
方便閱讀版:
https://i.imgur.com/jky1CZR.png

補充說明(Supplement):
ans跟ori兩個指標在主函式裡我是放入原題目給的指標
以及我複製他的val來建的新指標
Node* cloneGraph(Node* node) {
Node *ans;
vector<int> tfound;
if(!node) return nullptr;
ans = new Node(node->val);
dfs(ans, node, &tfound);
}
所以確定數值是一樣的
感謝各位!
--
作者 finzaghi (琴之森) 看板 C_Chat
標題 [閒聊] 果青 立體歐派抱枕
時間 Fri Apr 14 17:19:51 2017
推
04/14 17:20,
04/14 17:20
推
04/14 17:21,
04/14 17:21
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 106.1.232.193 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1742227061.A.964.html
※ 編輯: handofn0xus (106.1.232.193 臺灣), 03/18/2025 00:47:07
推
03/18 00:59,
20小時前
, 1F
03/18 00:59, 1F
→
03/18 01:03,
19小時前
, 2F
03/18 01:03, 2F
喔幹 對欸 完全沒注意到
但是即使如此 他看到同樣的數值 find那邊應該就會擋下來不再進下一層遞迴了?
但實際上他還是繼續走下去
※ 編輯: handofn0xus (220.130.45.59 臺灣), 03/18/2025 10:04:15
推
03/18 11:23,
9小時前
, 3F
03/18 11:23, 3F
推
03/18 15:30,
5小時前
, 4F
03/18 15:30, 4F
→
03/18 15:30,
5小時前
, 5F
03/18 15:30, 5F
C_and_CPP 近期熱門文章
11
46
PTT數位生活區 即時熱門文章