From b753294863d08fe994fb305fdd96d306b6e25b69 Mon Sep 17 00:00:00 2001 From: "akash.patil" Date: 2025年2月24日 21:46:34 +0530 Subject: [PATCH] Update BFS.cpp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Improvements: ✅ Fixed Memory Leak: visited is now a vector, and the destructor properly deallocates adjLists. ✅ Encapsulation: visited is now local to BFS, preventing unexpected behavior. ✅ Simplified Iteration: Used range-based for loop instead of an iterator for readability. ✅ Removed Redundant Edge Addition in main(). --- BFS in C++/BFS.cpp | 85 +++++++++++++++++++++++----------------------- 1 file changed, 43 insertions(+), 42 deletions(-) diff --git a/BFS in C++/BFS.cpp b/BFS in C++/BFS.cpp index ea69e4e0..9e07271e 100644 --- a/BFS in C++/BFS.cpp +++ b/BFS in C++/BFS.cpp @@ -1,63 +1,64 @@ #include #include +#include using namespace std; class Graph { - int numVertices; - list* adjLists; - bool* visited; - - public: - Graph(int vertices); - void addEdge(int src, int dest); - void BFS(int startVertex); + int numVertices; + list* adjLists; + +public: + Graph(int vertices); + ~Graph(); // Destructor to free memory + void addEdge(int src, int dest); + void BFS(int startVertex); }; Graph::Graph(int vertices) { - numVertices = vertices; - adjLists = new list[vertices]; + numVertices = vertices; + adjLists = new list[vertices]; +} + +Graph::~Graph() { + delete[] adjLists; // Free allocated memory } + void Graph::addEdge(int src, int dest) { - adjLists[src].push_back(dest); - adjLists[dest].push_back(src); + adjLists[src].push_back(dest); + adjLists[dest].push_back(src); } void Graph::BFS(int startVertex) { - visited = new bool[numVertices]; - for (int i = 0; i < numVertices; i++) - visited[i] = false; + vector visited(numVertices, false); // Avoids memory leaks - list queue; + list queue; + visited[startVertex] = true; + queue.push_back(startVertex); - visited[startVertex] = true; - queue.push_back(startVertex); + while (!queue.empty()) { + int currVertex = queue.front(); + cout << "Visited " << currVertex << " "; + queue.pop_front(); - list::iterator i; - - while (!queue.empty()) { - int currVertex = queue.front(); - cout << "Visited " << currVertex << " "; - queue.pop_front(); - - for (i = adjLists[currVertex].begin(); i != adjLists[currVertex].end(); ++i) { - int adjVertex = *i; - if (!visited[adjVertex]) { - visited[adjVertex] = true; - queue.push_back(adjVertex); - } + for (int adjVertex : adjLists[currVertex]) { + if (!visited[adjVertex]) { + visited[adjVertex] = true; + queue.push_back(adjVertex); + } + } } - } + cout << endl; } int main() { - Graph g(4); - g.addEdge(0, 1); - g.addEdge(0, 2); - g.addEdge(1, 2); - g.addEdge(2, 0); - g.addEdge(2, 3); - g.addEdge(3, 3); - g.BFS(2); - return 0; -} \ No newline at end of file + Graph g(4); + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 3); + g.addEdge(3, 3); + + g.BFS(2); + return 0; +}

AltStyle によって変換されたページ (->オリジナル) /