You are on page 1of 15

ARTIFICIAL INTELLIGENCE

NAME:
HUSNAIN IQBAL

SECTION:
A

ASSIGNMENT #:
2

ROLL NUM:
UW-18-CS-BS-042

SUBMITTED TO:
MAM HIRA WASEEM

DATE:
11-03-2021

UNIVERSTY OF WAH
Create a program in Java that perform the following search strategies
● Breadth First Search
● Depth first Search
● Uniform Cost Search
● Iterative Deepening
● Depth Limited Search
And
● A* search
● Your program should have a menu that give user freedom to choose among any given option
Note: Your program should be capable of traversing the trees and give the optimal Solution.

CODE:
import java.util.*;

public class searchAlgo


{
public static void main(String argvs[])
{
int ch;

Scanner sc = new Scanner(System.in);

System.out.println("1: BFS");
System.out.println("2: DFS");
System.out.println("3: UCS");
System.out.println("5: DLS");
System.out.println("6: A* search");

while(true)
{
System.out.print("Make your choice: ");
ch = sc.nextInt(); // reading user's choice
switch (ch)
{
case 1:
BFS obj = new BFS();
obj.makeGraph(10);
obj.addEdgeToGraph(0, 1);
obj.addEdgeToGraph(0, 9);
obj.addEdgeToGraph(2, 3);
obj.addEdgeToGraph(2, 4);
obj.addEdgeToGraph(3, 5);
obj.addEdgeToGraph(3, 6);
obj.addEdgeToGraph(4, 7);
obj.addEdgeToGraph(4, 8);

System.out.println("BFS of graph is:");


obj.BFsearch(0);
break;

case 2:

Node node40 =new Node(40);


Node node10 =new Node(10);
Node node20 =new Node(20);
Node node30 =new Node(30);
Node node60 =new Node(60);
Node node50 =new Node(50);
Node node70 =new Node(70);

node40.addneighbours(node10);
node40.addneighbours(node20);
node10.addneighbours(node30);
node20.addneighbours(node10);
node20.addneighbours(node30);
node20.addneighbours(node60);
node20.addneighbours(node50);
node30.addneighbours(node60);
node60.addneighbours(node70);
node50.addneighbours(node70);

DepthFirstSearchExampleNeighbourList dfsExample = new DepthFirstSearchExampleNeighbourList();

System.out.println("The DFS traversal of the graph using stack ");


dfsExample.dfsUsingStack(node40);

System.out.println();

// Resetting the visited flag for nodes


node40.visited=false;
node10.visited=false;
node20.visited=false;
node30.visited=false;
node60.visited=false;
node50.visited=false;
node70.visited=false;
System.out.println("The DFS traversal of the graph using recursion ");
dfsExample.dfs(node40);

break;

case 3:
int adjacency_matrix[][];
int number_of_vertices;
int source = 0;
int destination = 0;
int distance;
Scanner scan = new Scanner(System.in);
try
{
System.out.println("Enter the number of vertices");
number_of_vertices = scan.nextInt();

adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];


System.out.println("Enter the Weighted Matrix for the graph");
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = scan.nextInt();
if (i == j)
{
adjacency_matrix[i][j] = 0;
continue;
}
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = MAX_VALUE;
}
}
}

System.out.println("Enter the source ");


source = scan.nextInt();

System.out.println("Enter the destination");


destination = scan.nextInt();

UniformCostSearch uniformCostSearch = new UniformCostSearch(number_of_vertices);


distance = uniformCostSearch.uniformCostSearch(adjacency_matrix,source, destination);
uniformCostSearch.printPath();
System.out.println("\nThe Distance between source " + source +
" and destination " + destination + " is " + distance);

} catch (InputMismatchException inputMismatch)


{
System.out.println("Wrong Input Format");
}
scan.close();
}

break;

case 4:
IDfS();
break;

case 5:
ASS();
break;

default:
System.out.println("Invalid choice! Please make a valid choice. \n\n");
}
}
}
}

● Breadth First Search

import java.util.*;
import java.util.Queue;

public class BFS{


private int n;
private LinkedList<Integer> adjList[];
private Queue<Integer> q = new LinkedList();

// creating adjacency list for each vertex.


public void makeGraph(int no)
{
n = no;
adjList = new LinkedList[no];

int i;

for (i= 0; i < no; i++)


{
adjList[i] = new LinkedList();
}
}

// adding edges to graph


public void addEdgeToGraph(int u, int v)
{
adjList[u].add(v);
}

//BFtravesal function traverse one connected component of graph


public void BFtraversal(int v, boolean[] visited)
{
q.add(v);
visited[v] = true;

int k;

while( !q.isEmpty() )
{
k = q.remove();
System.out.print( k +" ");
// we are iterating through adjacency list of vertex k which has to be explored now.
// it will give the adjacent nodes of each vertex.
Iterator<Integer> i = adjList[k].listIterator();
int j;

while( i.hasNext() )
{

j = i.next();
if( visited[j] != true )
{
// if any child found with out visiting then those child will be added to queue.
q.add(j);
visited[j] = true;
}
}
}
}

// BFsearch function will maintain boolean array to know which vertex is explored.
// If in case of disconnected graph it will again call BFtravesal on another component
public void BFsearch(int v)
{
boolean visited[] = new boolean[n];

BFtraversal(v, visited);
for ( int i = 0; i < n; i++ )
{
// after calling BFtraveral it is checking whether any vertex left out with out exploring
if( visited[i] != true )
{
// if found it will call again BFtraversal
BFtraversal(i, visited);
}
}
}

● Depth first Search

package org.arpit.java2blog;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class DepthFirstSearchExampleNeighbourList


{

static class Node


{
int data;
boolean visited;
List<Node> neighbours;

Node(int data)
{
this.data=data;
this.neighbours=new ArrayList<>();

}
public void addneighbours(Node neighbourNode)
{
this.neighbours.add(neighbourNode);
}
public List<Node> getNeighbours() {
return neighbours;
}
public void setNeighbours(List<Node> neighbours) {
this.neighbours = neighbours;
}
}

// Recursive DFS
public void dfs(Node node)
{
System.out.print(node.data + " ");
List<Node> neighbours=node.getNeighbours();
node.visited=true;
for (int i = 0; i < neighbours.size(); i++) {
Node n=neighbours.get(i);
if(n!=null && !n.visited)
{
dfs(n);
}
}
}

// Iterative DFS using stack


public void dfsUsingStack(Node node)
{
Stack<Node> stack=new Stack<Node>();
stack.add(node);
while (!stack.isEmpty())
{
Node element=stack.pop();
if(!element.visited)
{
System.out.print(element.data + " ");
element.visited=true;
}

List<Node> neighbours=element.getNeighbours();
for (int i = 0; i < neighbours.size(); i++) {
Node n=neighbours.get(i);
if(n!=null && !n.visited)
{
stack.add(n);
}
}
}
}

public static void main(String arg[])


{
}
}

● Uniform Cost Search

import java.util.*;

public class UCS


{
private PriorityQueue<Node> priorityQueue;
private Set<Integer> settled;
private int distances[];
private int numberOfNodes;
private int adjacencyMatrix[][];
private LinkedList<Integer> path;
private int[] parent;
private int source, destination;
public static final int MAX_VALUE = 999;

public UniformCostSearch(int numberOfNodes)


{
this.numberOfNodes = numberOfNodes;
this.settled = new HashSet<Integer>();
this.priorityQueue = new PriorityQueue<>(numberOfNodes, new Node());
this.distances = new int[numberOfNodes + 1];
this.path = new LinkedList<Integer>();
this.adjacencyMatrix = new int[numberOfNodes + 1][numberOfNodes + 1];
this.parent = new int[numberOfNodes + 1];
}

public int uniformCostSearch(int adjacencyMatrix[][], int source, int destination)


{
int evaluationNode;
this.source = source;
this.destination = destination;

for (int i = 1; i <= numberOfNodes; i++)


{
distances[i] = MAX_VALUE;
}

for (int sourcevertex = 1; sourcevertex <= numberOfNodes; sourcevertex++)


{
for (int destinationvertex = 1; destinationvertex <= numberOfNodes; destinationvertex++)
{
this.adjacencyMatrix[sourcevertex][destinationvertex] =
adjacencyMatrix[sourcevertex[destinationvertex];
}
}

priorityQueue.add(new Node(source, 0));


distances[source] = 0;

while (!priorityQueue.isEmpty())
{
evaluationNode = getNodeWithMinDistanceFromPriorityQueue();
System.out.println("The eval Node is " + evaluationNode);
if (evaluationNode == destination)
{
return distances[destination];
}
settled.add(evaluationNode);
addFrontiersToQueue(evaluationNode);
}
return distances[destination];
}
private void addFrontiersToQueue(int evaluationNode)
{
for (int destination = 1; destination <= numberOfNodes; destination++)
{
if (!settled.contains(destination))
{
if (adjacencyMatrix[evaluationNode][destination] != MAX_VALUE)
{
if (distances[destination] > adjacencyMatrix[evaluationNode][destination]
+ distances[evaluationNode])
{
distances[destination] = adjacencyMatrix[evaluationNode][destination]
+ distances[evaluationNode];
parent[destination] = evaluationNode;
}

Node node = new Node(destination, distances[destination]);


if (priorityQueue.contains(node))
{
priorityQueue.remove(node);
}
priorityQueue.add(node);
}
}
}
}

private int getNodeWithMinDistanceFromPriorityQueue()


{
Node node = priorityQueue.remove();
return node.node;
}

public void printPath()


{
path.add(destination);
boolean found = false;
int vertex = destination;
while (!found)
{
if (vertex == source)
{
found = true;
continue;
}
path.add(parent[vertex]);
vertex = parent[vertex];
}
System.out.println("The Path between " + source + " and " + destination+ " is ");
Iterator<Integer> iterator = path.descendingIterator();
while (iterator.hasNext())
{
System.out.print(iterator.next() + "\t");
}
}

public static void main(String... arg)


{
}

class Node implements Comparator<Node>


{
public int node;
public int cost;

public Node()
{

public Node(int node, int cost)


{
this.node = node;
this.cost = cost;
}

@Override
public int compare(Node node1, Node node2)
{
if (node1.cost < node2.cost)
return -1;
if (node1.cost > node2.cost)
return 1;
if (node1.node < node2.node)
return -1;
return 0;
}

@Override
public boolean equals(Object obj)
{
if (obj instanceof Node)
{
Node node = (Node) obj;
if (this.node == node.node)
{
return true;
}
}
return false;
}
}
● Iterative Deepening
import java.util.*;

public class ASS{

public static class PriorityList extends LinkedList {

public void add(Comparable object) {


for (int i=0; i<size(); i++) {
if (object.compareTo(get(i)) <= 0) {
add(i, object);
return;
}
}
addLast(object);
}
}

protected List constructPath(AStarNode node) {


LinkedList path = new LinkedList();
while (node.pathParent != null) {
path.addFirst(node);
node = node.pathParent;
}
return path;
}

public List findPath(AStarNode startNode, AStarNode goalNode) {

PriorityList openList = new PriorityList();


LinkedList closedList = new LinkedList();

startNode.costFromStart = 0;
startNode.estimatedCostToGoal =
startNode.getEstimatedCost(goalNode);
startNode.pathParent = null;
openList.add(startNode);

while (!openList.isEmpty()) {
AStarNode node = (AStarNode)openList.removeFirst();
if (node == goalNode) {
return constructPath(goalNode);
}
List neighbors = node.getNeighbors();
for (int i=0; i<neighbors.size(); i++) {
AStarNode neighborNode =
(AStarNode)neighbors.get(i);
boolean isOpen = openList.contains(neighborNode);
boolean isClosed =
closedList.contains(neighborNode);
float costFromStart = node.costFromStart +
node.getCost(neighborNode);

if ((!isOpen && !isClosed) ||


costFromStart < neighborNode.costFromStart)
{
neighborNode.pathParent = node;
neighborNode.costFromStart = costFromStart;
neighborNode.estimatedCostToGoal =
neighborNode.getEstimatedCost(goalNode);
if (isClosed) {
closedList.remove(neighborNode);
}
if (!isOpen) {
openList.add(neighborNode);
}
}
}
closedList.add(node);
}
return null;
}

}
● Depth Limited Search
package iterative_deepening_dfs.java.simple;

public class IDFS {

private static boolean bottomReached = false;

public static Node iterativeDeepeningDFS(Node start, int target) {

int depth = 1;

while (!bottomReached) {

bottomReached = true;

Node result = iterativeDeepeningDFS(start, target, 0, depth);

if (result != null) {

return result;
}

depth *= 2;

System.out.println("Increasing depth to " + depth);

return null;

private static Node iterativeDeepeningDFS(Node node, int target, int currentDepth, int maxDepth) {

System.out.println("Visiting Node " + node.value);

if (node.value == target) {

System.out.println("Found the node we're looking for!");

return node;

if (currentDepth == maxDepth) {

System.out.println("Current maximum depth reached, returning...");

if (node.children.length > 0) {

bottomReached = false;

return null;

for (int i = 0; i < node.children.length; i++) {

Node result = iterativeDeepeningDFS(node.children[i], target, currentDepth + 1, maxDepth);

if (result != null) {

return result;

return null;

}
class Node {

Node[] children;

int value;

You might also like