using BFS to find shortest path.

Let's say I have a graph using strings, such as locations. I want to be able to get from
x to y in the shortest path possible. X and Y are user defined.
I've never used BFS, but I've seen some samples online. However, these all used integers as data and I'm not sure how to implement it using strings. I know you have to implement a Queue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <string>
#include <iomanip>
#include <iostream>

using namespace std;

struct node
{
	string info;
	node *next;
};
class Queue 
{
private:
	node *front;
	node *rear;
public:
		Queue();
		~Queue();
		bool isEmpty();
		void enqueue(string);
		string dequeue();
		void display();
};
Queue::Queue()
{
	front = NULL;
	rear = NULL;
}
Queue::~Queue()
{
	delete front;
}

void Queue::enqueue(string data)
{
	node *temp = new node();
	temp->info = data;
	temp->next = NULL;
	if(front == NULL)
	{
		front = temp;
	}
	else
	{
		rear->next = temp;
	}
	rear = temp;
}

string Queue::dequeue()
{
	node *temp = new node();
	string value;
	if(front == NULL)
	{
		cout<<"Queue is empty"<<endl;
	}
	else
	{
		temp = front;
		value = temp->info;
		front = front->next;
		delete temp;
	}
	return value;
}

bool Queue::isEmpty()
{
	return(front == NULL);
}




how would I go writing the BFS? Not asking anyone to write it for me, just need a general direction since I am a beginner. I'm sort of stuck.

Thanks.
Oh forgot to include that I already have the Graph implemented. Such as existsEdge, addEdge, addVertex. vertexList, adjacencyList. I can include it in the code if anyone needs me too.
Last edited on
bump.
BFS doesn't really change from data type to data type since you are only trying to find the shortest path. What specifically are you having trouble doing?
perhaps you should look at http://en.wikipedia.org/wiki/Breadth-first_search it has pseudo code that you should be able to adapt fairly easily and it actually has examples about using it on german cities.
Topic archived. No new replies allowed.