ผมมีรายการขอบดังนี้ครับ
75 77
77 78
78 79
60 63
61 65
65 67
57 62
62 64
67 81
81 85
ฉันต้องการแยกขอบที่เชื่อมต่อดังนี้
75 60 61 57
77 63 65 62
78 67 64
79 81
85
ฉันเขียนโค้ดต่อไปนี้ใน Matlab
edges = [75 77; 77 78; 78 79; 60 63; 61 65; 65 67; 57 62; 62 64; 67 81; 81 85];
visited = zeros(size(edges,1),1);
cEdges = [];
cEdgesC = 1;
cEdges(1,cEdgesC) = edges(1,1);
cEdges(2,cEdgesC) = edges(1,2);
visited(1,1) = 1;
orgR = 1;
orgC = 2;
while sum(visited) <= size(visited,1)
cEdgesR = nnz(cEdges(:,cEdgesC));
currentVertex = cEdges(cEdgesR,cEdgesC);
fprintf('\n%d\t%d',cEdgesR,currentVertex);
[foundR,foundC] = find(edges==currentVertex);
foundR(foundR==orgR) = [];
foundC(foundC==orgC) = [];
while isempty(foundR)
fmt=repmat('%d ',1,cEdgesR);
fprintf('\nLoop found: ');
fprintf(fmt,(cEdges(:,cEdgesC))');
cEdgesC = cEdgesC+1;
orgR = find(visited==0, 1, 'first');
orgC = 1;
cEdges(1,cEdgesC) = edges(orgR,orgC);
cEdges(2,cEdgesC) = edges(orgR,orgC+1);
visited(orgR,1) = 1;
cEdgesR = nnz(cEdges(:,cEdgesC));
currentVertex = cEdges(2,cEdgesC);
fprintf('\n%d\t%d',cEdgesR,currentVertex);
[foundR,foundC]=find(edges==currentVertex);
foundR(foundR==orgR) = [];
foundC(foundC==orgC) = [];
if isempty(foundR)
// What to do here?
end
end
fprintf('\t%d\t%d',foundR,foundC);
orgR = foundR;
if foundC == 1
cEdges(cEdgesR+1,1) = edges(foundR,foundC+1);
orgC = foundC+1;
else
cEdges(cEdgesR+1,1) = edges(foundR,foundC-1);
orgC = foundC-1;
end
visited(foundR,1) = 1;
end
รหัสทำงานเป็นวงวนโดยไม่หยุด ฉันรู้สึกว่าปัญหาอยู่ที่ส่วนท้ายของ while วงใน ฉันจะกระโดดกลับไปยังจุดเริ่มต้นของวงในขณะที่ด้านในได้อย่างไร หากตรงตามเงื่อนไขเดียวกันที่จุดสิ้นสุดอีกครั้ง ขอบคุณ