What's wrong with my Breadth-First-Search (BFS) Algorithm

[C++]

For this lab I was forced to use a map for the BFS algorithm. I know I'm really close to the correct thing, but there is something wrong about my code, but I can't seem to figure it out. Thanks for anyone who takes the time to look through my code. :)

​

27 int Graph::BFS(char s, char t, map<char, int>&distance, map<char, char>& go_through) const

29 if(adjMap.find(s) != adjMap.end() | adjMap.find(t) != adjMap.end())

30 {

31 for(auto i = adjMap.begin(); i != adjMap.end(); i++)

32 {

33 distance[i->first] = NOPATH;

34 }

35 queue<char> q;

36 distance[s] = 0;

37 go_through[s] = s;

38 q.push(s);

39 char current = s;

40

41 while(!q.empty() && current != t)

42 {

43 current = q.front();

44 q.pop();

45

46 for(auto j = adjMap.begin(); j != adjMap.end(); j++)

47 {

48 if(distance[j->first] == NOPATH)

49 {

50 distance[j->first] = distance[current] +1;

51 go_through[j->first] = current;

52 q.push(j->first);

53 }

54 }

55 }

56 return distance[t];

57 }

58 else

59 {

60 return INVALID_VERTEX;

61 }

62 }

For some reason, my code is not outputting the expected results. I think it has something to do with the second for loop on line 46.

s = source node

t = target node

adjmap = map<char, set<char>>NOPATH = -1

Posted Apr 16, 2022, 4:15 PM UTC · edited

01

Should edit you post and make the code inside a code block so people will better be able to help.

4
[deleted]•

[deleted]

1