PSC Per.2
PSC Per.2
PSC Per.2
Jawaban:
1. Nama Kelompok :
1) Hari Fitri
2) Muhammad Rafli
3) Rhema Selvia Putri
4) Angella Karismanti
5) Esiska
2.
Algoritma Breadth First Search(BFS)
peta = { 'A': set (['B', 'F']),
'B': set (['A', 'C', 'F']),
'C': set (['B', 'D', 'E']),
'D': set (['C', 'E']),
'E': set (['C', 'D', 'F']),
'F': set (['A', 'B', 'E']),}
if mulai == tujuan :
return "Awal adalah Tujuan"
while queue :
jalur = queue.pop(0)
node = jalur[-1]
if neighbours == tujuan:
return jalur_baru
explored.append(node)
Output BFS:
while stack:
jalur = stack.pop()
node = jalur[-1]
if neighbours == tujuan:
return new_jalur
visited.add(node)
return None
mulai = 'A'
tujuan = 'D'
jalur = dfs(peta, mulai, tujuan)
if jalur:
print(f"Jalur terpendek dari {mulai} ke {tujuan} adalah:", "->".join(jalur))
else:
print(f"Tidak ada jalur dari {mulai} ke {tujuan}")
Output DFS:
Algoritma Greedy
import sys
class TSPGreedy:
def __init__(self, graph):
self.graph = graph
self.num_nodes = len(graph)
def tsp(self):
visited = [False] * self.num_nodes
# Mulai dari simpul 0
current_node = 0
visited[current_node] = True
path = [current_node]
total_cost = 0
total_cost += self.graph[current_node][next_node]
visited[next_node] = True
current_node = next_node
for i in range(self.num_nodes):
if not visited[i] and self.graph[current_node][i] < min_cost:
min_cost = self.graph[current_node][i]
next_node = i
return next_node
# Contoh penggunaan
if __name__ == "__main__":
graph = [
[0, 141, 181, 272],
[141, 0, 343, 363],
[181, 363, 0, 343],
[272, 343, 343, 0]
]
tsp_solver = TSPGreedy(graph)
path, total_cost = tsp_solver.tsp()
print("Rute terpendek:", path)
print("Jarak terpendek:", total_cost)
Output Greedy:
Algoritma a*
import heapq
class AStar:
def __init__(self, graph, heuristic):
self.graph = graph
self.num_nodes = len(graph)
self.heuristic = heuristic
path.append(start)
path.reverse()
return path
# Contoh penggunaan
if __name__ == "__main__":
# Contoh graph
graph = {
'A': {'B': 40, 'C': 131, 'D': 202},
'B': {'A': 40, 'C': 91, 'D': 162, 'E': 182},
'C': {'A': 131, 'B': 91, 'D': 71, 'E': 91},
'D': {'A': 202, 'B': 162, 'C': 71, 'E': 20},
'E': {'B': 182, 'C': 91, 'D': 20}
}
# Inisialisasi algoritma A*
astar = AStar(graph, heuristic)
Output a*:
for _ in range(max_iterations):
neighbors = problem.neighbors(current_state)
if not neighbors:
break
current_state = next_state
return current_state
# Contoh penggunaan
class Problem:
def initial_state(self):
return random.randint(0, 100)
if __name__ == "__main__":
problem = Problem()
solution = hill_climbing(problem, 10000)
print("Solusi terbaik:", solution)