Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
ID: 437818630.
NODE 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
N°
1 X X X
2 X X
3 X X
4 X
5 X X X
6 X
7
8 X
9
10 X X
11
12
13
14 X X
1. Write a code that explores the tree searching for the goal state by the Breath First
Search algorithm. The code must display each node explored at each iteration
edge(1,2).
edge(1,3).
edge(1,4).
edge(2,5).
edge(2,6).
edge(3,7).
edge(3,8).
edge(4,9).
edge(5,10).
edge(5,11).
edge(5,12).
edge(6,13).
edge(8,14).
edge(10,15).
edge(10,16).
edge(14,17).
breadth_first([[Goal|Path]|_],Goal,[Goal|Path],0).
breadth_first([Path|Queue],Goal,FinalPath,N) :-
extend(Path,NewPaths),
append(Queue,NewPaths,NewQueue),
breadth_first(NewQueue,Goal,FinalPath,M),
N is M+1.
extend([Node|Path],NewPaths) :-
findall([NewNode,Node|Path],
(edge(Node,NewNode),
\+ member(NewNode,Path)), % for avoiding loops
NewPaths).
Query:
?- breadth_first([[1]],5,P,N).
Result:
P = [5, 2, 1],
N=4.
2. Write a code that explores the tree searching for the goal state from the initial state
by the Depth First Search algorithm. The code must display each node explored at
each iteration
edge(1,2).
edge(1,3).
edge(1,4).
edge(2,5).
edge(2,6).
edge(3,7).
edge(3,8).
edge(4,9).
edge(5,10).
edge(5,11).
edge(5,12).
edge(6,13).
edge(8,14).
edge(10,15).
edge(10,16).
edge(14,17).
depth_first([[Goal|Path]|_],Goal,[Goal|Path],0).
depth_first([Path|Queue],Goal,FinalPath,N) :-
extend(Path,NewPaths),
append(NewPaths,Queue,NewQueue),
depth_first(NewQueue,Goal,FinalPath,M),
N is M+1.
extend([Node|Path],NewPaths) :-
findall([NewNode,Node|Path],
(edge(Node,NewNode),
\+ member(NewNode,Path)), % for avoiding loops
NewPaths).
Query:
?- depth_first([[1]],5,P,N).
Result:
P = [5, 2, 1],
N=2.
3. How many nodes are explored by each algorithm BFS/(DFS before reaching the Goal?
We suppose that both the BFS and DFS algorithms will choose the right-most node first.
BFS Query:
?- breadth_first([[1]],17,P,N).
Result:
P = [17, 14, 8, 3, 1],
N = 16 .
16 nodes in BFS
DFS Query:
?- depth_first([[1]],17,P,N).
Result:
P = [17, 14, 8, 3, 1],
N = 14 .
14 nodes in DFS.