Sunteți pe pagina 1din 6

Uniform Cost Search

This article helps the beginner of an AI course to learn the objective and implementation of
Uninformed Search Strategies (Blind Search) which use only information available in the
problem definition.

Uninformed Search includes the following algorithms:


• Breadth First Search (BFS)
• Uniform Cost Search (UCS)
• Depth First Search (DFS)
• Depth Limited Search (DLS)
• Iterative Deepening Search (IDS)
• Bidirectional Search (BS)
This article covers several Search strategies that come under the heading of Uninformed
Search. The term means that the strategies have no additional information about States
beyond that provided in the problem definition. All they can do is generate successors and
distinguish a goal state from a non-goal state. All Search strategies are distinguished by
the order in which nodes are expanded.

To go ahead in these series, I will use some AI terminologies such as the following:
A problem can be defined by four components:
1. Initial State that the problem starts in
2. Goal State that the problem ends in
3. Finding sequences of actions that lead to Goal State
4. A path Cost to solve problem
Together, the initial state, goal state, actions and path cost define the state space of the
problem (the set of all states reachable from the initial state by any sequence of actions).
The path in the state space is a sequence of states connected by a sequence of actions. A
solution to the problem is an action sequence that leads from the initial state to the goal
state.
The process of looking at a sequence of actions that reaches the goal is called search. A
search algorithm takes a problem as input and returns a solution in the form of an action
sequences. The search starts from the initial state which represents the root node in the
problem search space. The branches are actions and the nodes corresponding to the
states in the problem state space.

Uniform cost search


Uniform cost search is a tree search algorithm related to breadth-first search. Whereas
breadth-first search determines a path to the goal state that has the least number of
edges, uniform cost search determines a path to the goal state that has the lowest weight.

Algorithm
Let T=(V,E) be a tree with weighted edges and let w(p) be the weight of path p in T. For
convenience, let r be the root of the tree and t(p) denote the end vertex of a path p in T.[1]
With that said, let K, the set of known paths starting with r, be {(r)}. It should be noted that
the weight of (r) is zero.
1. If there exists p in K such that p minimizes w(p) and t(p) is a goal state of T, i.e., a
leaf, stop. p is the path of minimal cost to the goal.
2. Otherwise, identify p in K where p minimizes w(p) and expand t(p). In other words,
add to K all paths formed by adding one of the child vertices of t(p) (if any) to p.
Remove p from K; it is considered 'visited', and failure to remove it may result in
non-termination of the search.
3. Repeat first step.
Code:

import java.util.Comparator; this.path = new LinkedList<Integer>();

import java.util.HashSet; this.adjacencyMatrix = new int[numberOfNodes +


1][numberOfNodes + 1];
import java.util.InputMismatchException;
this.parent = new int[numberOfNodes + 1];
import java.util.Iterator;
}
import java.util.LinkedList;

import java.util.PriorityQueue;
public int uniformCostSearch(int adjacencyMatrix[]
import java.util.Scanner; [], int source, int destination)

import java.util.Set; {

public class UniformCostSearch int evaluationNode;

{ this.source = source;

private PriorityQueue<Node> priorityQueue; this.destination = destination;

private Set<Integer> settled;

private int distances[]; for (int i = 1; i <= numberOfNodes; i++)

private int numberOfNodes; {

private int adjacencyMatrix[][]; distances[i] = MAX_VALUE;

private LinkedList<Integer> path; }

private int[] parent;

private int source, destination; for (int sourcevertex = 1; sourcevertex <=


numberOfNodes; sourcevertex++)
public static final int MAX_VALUE = 999;
{

for (int destinationvertex = 1; destinationvertex


public UniformCostSearch(int numberOfNodes) <= numberOfNodes; destinationvertex++)

{ {

this.numberOfNodes = numberOfNodes; this.adjacencyMatrix[sourcevertex]


[destinationvertex] =
this.settled = new HashSet<Integer>();

this.priorityQueue = new adjacencyMatrix[sourcevertex[destinationvertex];


PriorityQueue<>(numberOfNodes, new Node());
}
this.distances = new int[numberOfNodes + 1];
} {

distances[destination] =
adjacencyMatrix[evaluationNode][destination]
priorityQueue.add(new Node(source, 0));
+
distances[source] = 0; distances[evaluationNode];

parent[destination] = evaluationNode;

while (!priorityQueue.isEmpty()) }

evaluationNode = Node node = new Node(destination,


getNodeWithMinDistanceFromPriorityQueue(); distances[destination]);

System.out.println("The eval Node is " + if (priorityQueue.contains(node))


evaluationNode);
{
if (evaluationNode == destination)
priorityQueue.remove(node);
{
}
return distances[destination];
priorityQueue.add(node);
}
}
settled.add(evaluationNode);
}
addFrontiersToQueue(evaluationNode);
}
}
}
return distances[destination];

}
private int
getNodeWithMinDistanceFromPriorityQueue()

private void addFrontiersToQueue(int {


evaluationNode)
Node node = priorityQueue.remove();
{
return node.node;
for (int destination = 1; destination <=
numberOfNodes; destination++) }

if (!settled.contains(destination)) public void printPath()

{ {

if (adjacencyMatrix[evaluationNode] path.add(destination);
[destination] != MAX_VALUE)
boolean found = false;
{
int vertex = destination;
if (distances[destination] >
adjacencyMatrix[evaluationNode][destination] while (!found)

+ distances[evaluationNode]) {
if (vertex == source) adjacency_matrix = new
int[number_of_vertices + 1][number_of_vertices + 1];
{
System.out.println("Enter the Weighted Matrix
found = true; for the graph");

continue; for (int i = 1; i <= number_of_vertices; i++)

} {

path.add(parent[vertex]); for (int j = 1; j <= number_of_vertices; j++)

vertex = parent[vertex]; {

} adjacency_matrix[i][j] = scan.nextInt();

if (i == j)

System.out.println("The Path between " + source {


+ " and " + destination+ " is ");
adjacency_matrix[i][j] = 0;
Iterator<Integer> iterator =
path.descendingIterator(); continue;

while (iterator.hasNext()) }

{ if (adjacency_matrix[i][j] == 0)

System.out.print(iterator.next() + "\t"); {

} adjacency_matrix[i][j] = MAX_VALUE;

} }

public static void main(String... arg) }

int adjacency_matrix[][]; System.out.println("Enter the source ");

int number_of_vertices; source = scan.nextInt();

int source = 0;

int destination = 0; System.out.println("Enter the destination");

int distance; destination = scan.nextInt();

Scanner scan = new Scanner(System.in);

try UniformCostSearch uniformCostSearch = new


UniformCostSearch(number_of_vertices);
{
distance =
System.out.println("Enter the number of uniformCostSearch.uniformCostSearch(adjacency_m
vertices"); atrix,source, destination);

number_of_vertices = scan.nextInt(); uniformCostSearch.printPath();


System.out.println("\nThe Distance between
source " + source +
@Override
" and destination " + destination + " is
" + distance); public int compare(Node node1, Node node2)

} catch (InputMismatchException inputMismatch) if (node1.cost < node2.cost)

{ return -1;

System.out.println("Wrong Input Format"); if (node1.cost > node2.cost)

} return 1;

scan.close(); if (node1.node < node2.node)

} return -1;

} return 0;

class Node implements Comparator<Node>

{ @Override

public int node; public boolean equals(Object obj)

public int cost; {

if (obj instanceof Node)

public Node() {

{ Node node = (Node) obj;

if (this.node == node.node)

} {

return true;

public Node(int node, int cost) }

{ }

this.node = node; return false;

this.cost = cost; }

} }

$javac UniformCostSearch.java
$java UniformCostSearch
Enter the number of vertices
7
Enter the Weighted Matrix for the graph
0503000
0010000
0000608
0000220
0400000
0000003
0000400
Enter the source
1
Enter the destination
7
The Path between 1 and 7 is
1 4 6 7
The Distance between source 1 and destination 7 is 8

S-ar putea să vă placă și