forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Breadth_First_Search.rb
92 lines (61 loc) · 2.11 KB
/
Breadth_First_Search.rb
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
## Breadth First Search algorithm in Ruby.
def breadth_first_search(adj_matrix, source, destination)
node_array = [source]
path = []
## puts "\nThe initial NODE ARRAY is #{node_array}."
loop do
curr_node = node_array.pop
path << curr_node
## puts "The next node to be checked is #{curr_node}."
if curr_node.nil?
puts 'Destination Node Not Found!'
return false
elsif curr_node == destination
puts "\nDestination Node #{curr_node} Found!"
puts "\nThe path between Source Node #{source} and Destination Node #{destination} is:\n #{path}."
return true
end
## puts "\nIterating through the following array:\n #{adj_matrix[curr_node]}"
children = (0..adj_matrix.length - 1).to_a.select do |i|
## puts "Checking index #{i} whose value is #{adj_matrix[curr_node][i]}"
adj_matrix[curr_node][i] == 1
end
## puts "\nCHILD ARRAY returned: #{children}"
node_array = children + node_array
## puts "\nAfter appending CHILD ARRAY, NODE ARRAY is: #{node_array}"
end
end
## Defining Adjacency Matrix by taking user input
puts "Enter Size of Adjacency Matrix: "
size = gets.to_i
adj_matrix = Array.new(size) { [] }
i = 0
counter = 0
while(counter != size)
i = 0
puts "\nEnter the values of row #{counter + 1}: "
while(i != size)
adj_matrix[counter][i] = gets.to_i
i += 1
end
counter += 1
end
## User input for Source Node and Destination Node
puts "\nEnter Source Node: "
source = gets.to_i
puts "\nEnter Destination Node: "
destination = gets.to_i
## Passing the adjacent matrix, source and destination as arguments to the algorithm.
breadth_first_search(adj_matrix, source, destination)
=begin
Enter Size of Adjacency Matrix: 4
Enter the values of row 1: 0 1 1 0
Enter the values of row 2: 1 0 0 0
Enter the values of row 3: 1 0 1 0
Enter the values of row 4: 0 1 0 0
Enter Source Node: 0
Enter Destination Node: 2
Destination Node 2 Found!
The path between Source Node 0 and Destination Node 2 is:
[0, 2].
=end