applied programming

23
Engr. Abdul-Rahman Mahmood DPM, MCP, QMR(ISO9001:2000) [email protected] [email protected] alphapeeler.sf.net/pubkeys/pkey.htm http://alphapeeler.sourceforge.net pk.linkedin.com/in/armahmood http://alphapeeler.tumblr.com www.twitter.com/alphapeeler [email protected] www.facebook.com/alphapeeler [email protected] abdulmahmood-sss alphasecure mahmood_cubix 48660186 [email protected] [email protected] http://alphapeeler.sf.net/me http://alphapeeler.sf.net/acms/ Applied Programming

Upload: others

Post on 16-Oct-2021

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Applied Programming

Engr. Abdul-Rahman MahmoodDPM, MCP, QMR(ISO9001:2000)

[email protected] [email protected]

alphapeeler.sf.net/pubkeys/pkey.htm http://alphapeeler.sourceforge.net

pk.linkedin.com/in/armahmood http://alphapeeler.tumblr.com

www.twitter.com/alphapeeler [email protected]

www.facebook.com/alphapeeler [email protected]

abdulmahmood-sss alphasecure mahmood_cubix 48660186

[email protected] [email protected]

http://alphapeeler.sf.net/me http://alphapeeler.sf.net/acms/

Applied Programming

Page 2: Applied Programming

Graphs

Page 3: Applied Programming

A graph can be defined as group of vertices and edges that are used to connect these vertices. A graph can be seen as a cyclic tree, where the vertices (Nodes) maintain any complex relationship among them instead of having parent child relationship.

In the above graph,

V = {a, b, c, d, e}

E = {ab, ac, bd, cd, de}

Graph and its representations

Page 4: Applied Programming

A graph G can be defined as an ordered set G(V, E) where V(G) represents the set of vertices and E(G) represents the set of edges which are used to connect these vertices.

A Graph G(V, E) with 5 vertices (A, B, C, D, E) and six edges ((A,B), (B,C), (C,E), (E,D), (D,B), (D,A)) is shown in the following figure.

Definition

Page 5: Applied Programming

A graph can be directed or undirected. However, in an undirected graph, edges are not associated with the directions with them. An undirected graph is shown in the above figure since its edges are not attached with any of the directions. If an edge exists between vertex A and B then the vertices can be traversed from B to A as well as A to B.

Undirected Graph

Page 6: Applied Programming

In a directed graph, edges form an ordered pair. Edges represent a specific path from some vertex A to another vertex B. Node A is called initial node while node B is called terminal node.

A directed graph is shown in the following figure.

Directed Graph

Page 7: Applied Programming

Path: A path can be defined as the sequence of nodes that are followed in order to reach some terminal node V from the initial node U.

Closed Path: A path will be called as closed path if the initial node is same as terminal node. A path will be closed path if V0=VN.

Simple Path: If all the nodes of the graph are distinct with an exception V0=VN, then such path P is called as closed simple path.

Cycle: A cycle can be defined as the path which has no repeated edges or vertices except the first and last vertices.

Graph Terminology

Page 8: Applied Programming

Connected Graph: A connected graph is the one in which some path exists between every two vertices (u, v) in V. There are no isolated nodes in connected graph.

Complete Graph: A complete graph is the one in which every node is connected with all other nodes. A complete graph contain n(n-1)/2 edges where n is the number of nodes in the graph.

Weighted Graph: In a weighted graph, each edge is assigned with some data such as length or weight. The weight of an edge e can be given as w(e) which must be a positive (+) value indicating the cost of traversing the edge.

Graph Terminology

Page 9: Applied Programming

Digraph: A digraph is a directed graph in which each edge of the graph is associated with some direction and the traversing can be done only in the specified direction.

Loop: An edge that is associated with the similar end points can be called as Loop.

Adjacent Nodes: If two nodes u and v are connected via an edge e, then the nodes u and v are called as neighbours or adjacent nodes.

Degree of the Node: A degree of a node is the number of edges that are connected with that node. A node with degree 0 is called as isolated node.

Graph Terminology

Page 10: Applied Programming

In sequential representation, we use adjacency matrix to store the mapping represented by vertices and edges. In adjacency matrix, the rows and columns are represented by the graph vertices. A graph having n vertices, will have a dimension n x n.

Sequential Representation

Page 11: Applied Programming

An entry Mij in the adjacency matrix representation of an undirected graph G will be 1 if there exists an edge between Vi and Vj.

An undirected graph and its adjacency matrix representation is shown in the following figure.

In the above figure, we can see the mapping among the vertices (A, B, C, D, E) is represented by using the adjacency matrix which is also shown in the figure.

Adjacency Matrix

Page 12: Applied Programming

There exists different adjacency matrices for the directed and undirected graph. In directed graph, an entry Aij will be 1 only when there is an edge directed from Vi to Vj. A directed graph and its adjacency matrix representation is shown in the following figure.

Adjacency Matrix

Page 13: Applied Programming

Representation of weighted directed graph is different. Instead of filling the entry by 1, the Non- zero entries of the adjacency matrix are represented by the weight of respective edges.

The weighted directed graph along with the adjacency matrix representation is shown in the following figure.

weighted directed graph

Page 14: Applied Programming

Depth First Search (DFS) algorithm traverses a graph in a depthward motion and uses a stack to remember to get the next vertex to start a search, when a dead end occurs in any iteration.

Depth First Traversal

As in the example given above, DFS algorithm

traverses from S to A to D to G to E to B first, then

to F and lastly to C. It employs the following rules.

•Rule 1 − Visit the adjacent unvisited vertex. Mark

it as visited. Display it. Push it in a stack.

•Rule 2 − If no adjacent vertex is found, pop up a

vertex from the stack. (It will pop up all the vertices

from the stack, which do not have adjacent

vertices.)

•Rule 3 − Repeat Rule 1 and Rule 2 until the stack

is empty.

Page 15: Applied Programming

Breadth First Search (BFS) algorithm traverses a graph in a breadthward motion and uses a queue to remember to get the next vertex to start a search, when a dead end occurs in any iteration.

Breadth First Search (BFS)

As in the example given above, BFS algorithm

traverses from A to B to E to F first then to C and G

lastly to D. It employs the following rules.

Rule 1 − Visit the adjacent unvisited vertex. Mark it

as visited. Display it. Insert it in a queue.

Rule 2 − If no adjacent vertex is found, remove the

first vertex from the queue.

Rule 3 − Repeat Rule 1 and Rule 2 until the queue

is empty.

Page 16: Applied Programming

See class notes for Depth First and Breadth First Traversal algorithms

Week13_Class_Notes_GraphsDepthFirstBreadthFirstAlgos.pdf

https://www.javatpoint.com/breadth-first-search-algorithm

https://www.javatpoint.com/depth-first-search-algorithm

Class notes & Reading material

Page 17: Applied Programming

Adjacency Matrix

Page 18: Applied Programming

Adjacency List:

Page 19: Applied Programming

Ex01import java.util.LinkedList; public class GraphAdjacencyList {

// A user define class to represent a graph. A graph is an array of adjacency lists. // Size of array will be V (number of vertices in graph) static class Graph {

int V; LinkedList<Integer> adjListArray[]; // constructor Graph(int V) {

this.V = V; // define the size of array as number of vertices adjListArray = new LinkedList[V]; // Create a new list for each vertex // such that adjacent nodes can be stored for(int i = 0; i < V ; i++){

adjListArray[i] = new LinkedList<>(); }

} }

// Adds an edge to an undirected graph static void addEdge(Graph graph, int src, int dest) {

// Add an edge from src to dest. graph.adjListArray[src].add(dest); // Since graph is undirected, add an edge from dest to src also graph.adjListArray[dest].add(src);

}

Page 20: Applied Programming

Ex01// A utility function to print the adjacency list representation of graph

static void printGraph(Graph graph) { for(int v = 0; v < graph.V; v++) {

System.out.println("Adjacency list of vertex "+ v); System.out.print("head"); for(Integer pCrawl: graph.adjListArray[v]){

System.out.print(" -> "+pCrawl); } System.out.println("\n");

} } // Driver program to test above functions public static void main(String args[]) {

// create the graph given in above figure int V = 5; Graph graph = new Graph(V); addEdge(graph, 0, 1); addEdge(graph, 0, 4); addEdge(graph, 1, 2); addEdge(graph, 1, 3); addEdge(graph, 1, 4); addEdge(graph, 2, 3); addEdge(graph, 3, 4); // print the adjacency list representation of // the above graph printGraph(graph);

} }

Output:Adjacency list of vertex 0head -> 1 -> 4

Adjacency list of vertex 1head -> 0 -> 2 -> 3 -> 4

Adjacency list of vertex 2head -> 1 -> 3

Adjacency list of vertex 3head -> 1 -> 2 -> 4

Adjacency list of vertex 4head -> 0 -> 1 -> 3

Page 21: Applied Programming

Ex 02 : Diagraphimport java.util.ArrayList;import java.util.Arrays;import java.util.List;

public class DigraphUsingAdjacencyList {// data structure to store graph edgesstatic class Edge {int src, dest;Edge(int src, int dest){this.src = src;this.dest = dest;}};// A list of lists to represent adjacency listList<List<Integer>> adj = new ArrayList<>();

// Constructor to construct graphpublic DigraphUsingAdjacencyList(List<Edge> edges){// allocate memory for adjacency listfor (int i = 0; i < edges.size(); i++)adj.add(i, new ArrayList<>());

// add edges to the undirected graphfor (Edge current : edges){// allocate new node in adjacency List from src to destadj.get(current.src).add(current.dest);

// Uncomment line 38 for undirected graph

// allocate new node in adjacency List from dest to src// adj.get(current.dest).add(current.src);}}

Page 22: Applied Programming

Ex 02 : Diagraph// print adjacency list representation of graphprivate static void printGraph(DigraphUsingAdjacencyListgraph){int src = 0;int n = graph.adj.size();

while (src < n){// print current vertex and all its neighboring verticesfor (int dest : graph.adj.get(src))System.out.print("(" + src + " --> " + dest + ")\t");

System.out.println();src++;}}

// Directed Graph Implementation in Javapublic static void main (String[] args){// Input: List of edges in a digraph (as per above diagram)List<Edge> edges = Arrays.asList(new Edge(0, 1), new Edge(1, 2), new Edge(2, 0), new Edge(2, 1),new Edge(3, 2), new Edge(4, 5), new Edge(5, 4));

// construct graph from given list of edgesDigraphUsingAdjacencyList graph = newDigraphUsingAdjacencyList(edges);

// print adjacency list representation of the graphprintGraph(graph);}}

Output: (0 --> 1)

(1 --> 2)

(2 --> 0) (2 --> 1)

(3 --> 2)

(4 --> 5)

(5 --> 4)

Page 23: Applied Programming

Please implement code presented in graphCode.pdf for adjacency matrix. This code does not use any built-in library for data structures.

Ex03