ソースを参照

Src Code Java Unid 4

george 6 ヶ月 前
コミット
9958a36b01

+ 63 - 0
unidad4/java/BSP/BFS.java

@@ -0,0 +1,63 @@
+// Function to find BFS of Graph from given source s
+import java.util.*;
+
+class BFS {
+
+    // BFS from given source s
+    static ArrayList<Integer> bfs(
+        ArrayList<ArrayList<Integer>> adj) {
+        int V = adj.size();
+        
+        int s = 0; // source node
+        // create an array to store the traversal
+        ArrayList<Integer> res = new ArrayList<>();
+        
+        // Create a queue for BFS
+        Queue<Integer> q = new LinkedList<>();
+        
+        // Initially mark all the vertices as not visited
+        boolean[] visited = new boolean[V];
+        
+        // Mark source node as visited and enqueue it
+        visited[s] = true;
+        q.add(s);
+        
+        // Iterate over the queue
+        while (!q.isEmpty()) {
+            
+            // Dequeue a vertex from queue and store it
+            int curr = q.poll();
+            res.add(curr);
+            
+            // Get all adjacent vertices of the dequeued 
+            // vertex curr If an adjacent has not been 
+            // visited, mark it visited and enqueue it
+            for (int x : adj.get(curr)) {
+                if (!visited[x]) {
+                    visited[x] = true;
+                    q.add(x);
+                }
+            }
+        }
+        return res;
+    }
+    
+    public static void main(String[] args) {
+        
+        // create the adjacency list
+        // { {2, 3, 1}, {0}, {0, 4}, {0}, {2} }
+       
+        ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
+        adj.add(new ArrayList<>(Arrays.asList(1, 2)));
+        adj.add(new ArrayList<>(Arrays.asList(0, 2, 3)));       
+        adj.add(new ArrayList<>(Arrays.asList(0, 4)));       
+        adj.add(new ArrayList<>(Arrays.asList(1,4)));          
+        adj.add(new ArrayList<>(Arrays.asList(2,3)));          
+        
+        
+        ArrayList<Integer> ans = bfs(adj);
+        for (int i : ans) {
+            System.out.print(i + " ");
+        }
+    }
+}

+ 46 - 0
unidad4/java/BinaryTree/BinarySearch.java

@@ -0,0 +1,46 @@
+// Java implementation of recursive
+// Binary Search
+
+class BinarySearch {
+	// Function that returns index of
+	// x if it is present in arr[l, r]
+	int binarySearch(int arr[], int l,int r, int x) {
+		if (r >= l) {
+			int mid = l + (r - l) / 2;
+			// If the element is present
+			// at the middle itself
+			if (arr[mid] == x)
+				return mid;
+
+			// If element is smaller than
+			// mid, then it can only be
+			// present in left subarray
+			if (arr[mid] > x)
+				return binarySearch(arr, l, mid - 1, x);
+			// Else the element can only be
+			// present in right subarray
+			return binarySearch(arr, mid + 1, r, x);
+		}
+		// Reach here when element is
+		// not present in array
+		return -1;
+	}
+
+	// Driver Code
+	public static void main(String args[]) {
+		// Create object of this class
+		BinarySearch ob = new BinarySearch();
+		// Given array arr[]
+		int arr[] = { 2, 3, 4, 10, 40 };
+		int n = arr.length;
+		int x = 10;
+
+		// Function Call
+		int result = ob.binarySearch(arr, 0, n - 1, x);
+
+		if (result == -1)
+			System.out.println("Element " + "not present");
+		else
+			System.out.println("Element found" + " at index " + result);
+	}
+}

+ 101 - 0
unidad4/java/BinaryTree/BinaryTreeDelete.java

@@ -0,0 +1,101 @@
+import java.util.LinkedList;
+import java.util.Queue;
+
+class Node {
+    int data;
+    Node left, right;
+
+    Node(int d) {
+        data = d;
+        left = right = null;
+    }
+}
+
+class BinaryTreeDelete {
+    // Function to delete a node from the binary tree
+    static Node deleteNode(Node root, int val) {
+        if (root == null) return null;
+
+        // Use a queue to perform BFS
+        Queue<Node> q = new LinkedList<>();
+        q.add(root);
+        Node target = null;
+
+        // Find the target node
+        while (!q.isEmpty()) {
+            Node curr = q.poll();
+
+            if (curr.data == val) {
+                target = curr;
+                break;
+            }
+            if (curr.left != null) q.add(curr.left);
+            if (curr.right != null) q.add(curr.right);
+        }
+        if (target == null) return root;
+
+        // Find the deepest rightmost node and its parent
+        Node lastNode = null;
+        Node lastParent = null;
+        Queue<Node> q1 = new LinkedList<>();
+        Queue<Node> parentQueue = new LinkedList<>();
+        q1.add(root);
+        parentQueue.add(null);
+
+        while (!q1.isEmpty()) {
+            Node curr = q1.poll();
+            Node parent = parentQueue.poll();
+
+            lastNode = curr;
+            lastParent = parent;
+
+            if (curr.left != null) {
+                q1.add(curr.left);
+                parentQueue.add(curr);
+            }
+            if (curr.right != null) {
+                q1.add(curr.right);
+                parentQueue.add(curr);
+            }
+        }
+
+        // Replace target's value with the last node's value
+        target.data = lastNode.data;
+
+        // Remove the last node
+        if (lastParent != null) {
+            if (lastParent.left == lastNode) lastParent.left = null;
+            else lastParent.right = null;
+        } else {
+            return null;
+        }
+        return root;
+    }
+
+    // In-order traversal
+    static void inorder(Node root) {
+        if (root == null) return;
+        inorder(root.left);
+        System.out.print(root.data + " ");
+        inorder(root.right);
+    }
+
+    public static void main(String[] args) {
+        Node root = new Node(2);
+        root.left = new Node(3);
+        root.right = new Node(4);
+        root.left.left = new Node(5);
+        root.left.right = new Node(6);
+
+        System.out.print("Original tree (in-order): ");
+        inorder(root);
+        System.out.println();
+
+        int valToDel = 3;
+        root = deleteNode(root, valToDel);
+
+        System.out.print("Tree after deleting " + valToDel + " (in-order): ");
+        inorder(root);
+        System.out.println();
+    }
+}

+ 66 - 0
unidad4/java/DSP/DFSGraph.java

@@ -0,0 +1,66 @@
+import java.util.*;
+
+public class DFSGraph {
+    // Recursive function for DFS traversal
+    private static void
+    dfsRec(ArrayList<ArrayList<Integer> > adj,
+           boolean[] visited, int s, ArrayList<Integer> res)
+    {
+        visited[s] = true;
+        res.add(s);
+
+        // Recursively visit all adjacent vertices that are
+        // not visited yet
+        for (int i : adj.get(s)) {
+            if (!visited[i]) {
+                dfsRec(adj, visited, i, res);
+            }
+        }
+    }
+
+    // Main DFS function that initializes the visited array
+    // and calls dfsRec
+    public static ArrayList<Integer>
+    DFS(ArrayList<ArrayList<Integer> > adj)
+    {
+        boolean[] visited = new boolean[adj.size()];
+        ArrayList<Integer> res = new ArrayList<>();
+        dfsRec(adj, visited, 0, res);
+        return res;
+    }
+
+    // To add an edge in an undirected graph
+    public static void
+    addEdge(ArrayList<ArrayList<Integer> > adj, int s,
+            int t)
+    {
+        adj.get(s).add(t);
+        adj.get(t).add(s);
+    }
+
+    public static void main(String[] args)
+    {
+        int V = 5;
+        ArrayList<ArrayList<Integer> > adj
+            = new ArrayList<>();
+
+        // Initialize adjacency list
+        for (int i = 0; i < V; i++) {
+            adj.add(new ArrayList<>());
+        }
+
+        // Add edges
+        int[][] edges= { { 1, 2 },{ 1, 0 },{ 2, 0 },{ 2, 3 },{ 2, 4 } }; 
+        for (int[] e : edges)
+        {
+            addEdge(adj, e[0], e[1]);
+        }
+
+        // Perform DFS starting from vertex 0
+        ArrayList<Integer> res = DFS(adj);
+
+        for (int i = 0; i < res.size(); i++) {
+            System.out.print(res.get(i) + " ");
+        }
+    }
+}

+ 151 - 0
unidad4/java/Grafo/Graph_generic.java

@@ -0,0 +1,151 @@
+// Java program to implement Graph
+// with the help of Generics
+
+import java.util.*;
+
+class Graph<T> {
+
+    // We use Hashmap to store the edges in the graph
+    private Map<T, List<T> > map = new HashMap<>();
+
+    // This function adds a new vertex to the graph
+    public void addVertex(T s)
+    {
+        map.put(s, new LinkedList<T>());
+    }
+
+    // This function adds the edge
+    // between source to destination
+    public void addEdge(T source, T destination,
+                        boolean bidirectional)
+    {
+
+        if (!map.containsKey(source))
+            addVertex(source);
+
+        if (!map.containsKey(destination))
+            addVertex(destination);
+
+        map.get(source).add(destination);
+        if (bidirectional == true) {
+            map.get(destination).add(source);
+        }
+    }
+
+    // This function gives the count of vertices
+    public void getVertexCount()
+    {
+        System.out.println("The graph has "
+                           + map.keySet().size()
+                           + " vertex");
+    }
+
+    // This function gives the count of edges
+    public void getEdgesCount(boolean bidirection)
+    {
+        int count = 0;
+        for (T v : map.keySet()) {
+            count += map.get(v).size();
+        }
+        if (bidirection == true) {
+            count = count / 2;
+        }
+        System.out.println("The graph has " + count
+                           + " edges.");
+    }
+
+    // This function gives whether
+    // a vertex is present or not.
+    public void hasVertex(T s)
+    {
+        if (map.containsKey(s)) {
+            System.out.println("The graph contains " + s
+                               + " as a vertex.");
+        }
+        else {
+            System.out.println("The graph does not contain "
+                               + s + " as a vertex.");
+        }
+    }
+
+    // This function gives whether an edge is present or
+    // not.
+    public void hasEdge(T s, T d)
+    {
+        if (map.get(s).contains(d)) {
+            System.out.println(
+                "The graph has an edge between " + s
+                + " and " + d + ".");
+        }
+        else {
+            System.out.println(
+                "The graph has no edge between " + s
+                + " and " + d + ".");
+        }
+    }
+  
+      public void neighbours(T s)
+    {
+        if(!map.containsKey(s)) 
+        return ;
+        System.out.println("The neighbours of "+s+" are");
+        for(T w:map.get(s))
+         System.out.print(w+",");
+    }
+
+    // Prints the adjancency list of each vertex.
+    @Override public String toString()
+    {
+        StringBuilder builder = new StringBuilder();
+
+        for (T v : map.keySet()) {
+            builder.append(v.toString() + ": ");
+            for (T w : map.get(v)) {
+                builder.append(w.toString() + " ");
+            }
+            builder.append("\n");
+        }
+
+        return (builder.toString());
+    }
+}
+
+// Driver Code
+public class Graph_generic {
+
+    public static void main(String args[])
+    {
+
+        // Object of graph is created.
+        
+        Graph<Integer> g = new Graph<Integer>();
+
+        // edges are added.
+        // Since the graph is bidirectional,
+        // so boolean bidirectional is passed as true.
+        g.addEdge(0, 1, true);
+        g.addEdge(0, 4, true);
+        g.addEdge(1, 2, true);
+        g.addEdge(1, 3, true);
+        g.addEdge(1, 4, true);
+        g.addEdge(2, 3, true);
+        g.addEdge(3, 4, true);
+
+        // Printing the graph
+        System.out.println("Graph:\n" + g.toString());
+
+        // Gives the no of vertices in the graph.
+        g.getVertexCount();
+
+        // Gives the no of edges in the graph.
+        g.getEdgesCount(true);
+
+        // Tells whether the edge is present or not.
+        g.hasEdge(3, 4);
+
+        // Tells whether vertex is present or not
+        g.hasVertex(5);
+               g.neighbours(1);
+
+    }
+}

+ 111 - 0
unidad4/java/Grafo_peso/Dijkstras.java

@@ -0,0 +1,111 @@
+import java.util.*;
+
+class Dijkstras {
+
+    // Construct adjacency list using ArrayList of ArrayList
+    static ArrayList<ArrayList<ArrayList<Integer>>> 
+                             constructAdj(int[][] edges, int V) {
+        // Initialize the adjacency list
+        ArrayList<ArrayList<ArrayList<Integer>>> 
+                                   adj = new ArrayList<>();
+
+        for (int i = 0; i < V; i++) {
+            adj.add(new ArrayList<>());
+        }
+
+        // Fill the adjacency list from edges
+        for (int[] edge : edges) {
+            int u = edge[0];
+            int v = edge[1];
+            int wt = edge[2];
+
+            // Add edge from u to v
+            ArrayList<Integer> e1 = new ArrayList<>();
+            e1.add(v);
+            e1.add(wt);
+            adj.get(u).add(e1);
+
+            // Since the graph is undirected, add edge from v to u
+            ArrayList<Integer> e2 = new ArrayList<>();
+            e2.add(u);
+            e2.add(wt);
+            adj.get(v).add(e2);
+        }
+
+        return adj;
+    }
+
+    // Returns shortest distances from src to all other vertices
+    static int[] dijkstra(int V, int[][] edges, int src) {
+        
+        // Create adjacency list
+        ArrayList<ArrayList<ArrayList<Integer>>> adj = 
+                               constructAdj(edges, V);
+
+        // PriorityQueue to store vertices to be processed
+        // Each element is a pair: [distance, node]
+        PriorityQueue<ArrayList<Integer>> pq = 
+          new PriorityQueue<>(Comparator.comparingInt(a -> a.get(0)));
+
+        // Create a distance array and initialize all distances as infinite
+        int[] dist = new int[V];
+        Arrays.fill(dist, Integer.MAX_VALUE);
+
+        // Insert source with distance 0
+        dist[src] = 0;
+        ArrayList<Integer> start = new ArrayList<>();
+        
+        start.add(0);
+        start.add(src);
+        pq.offer(start);
+
+        // Loop until the priority queue is empty
+        while (!pq.isEmpty()) {
+            
+            // Get the node with the minimum distance
+            ArrayList<Integer> curr = pq.poll();
+            int d = curr.get(0);
+            int u = curr.get(1);
+
+            // Traverse all adjacent vertices of the current node
+            for (ArrayList<Integer> neighbor : adj.get(u)) {
+                int v = neighbor.get(0);
+                int weight = neighbor.get(1);
+
+                // If there is a shorter path to v through u
+                if (dist[v] > dist[u] + weight) {
+                    // Update distance of v
+                    dist[v] = dist[u] + weight;
+
+                    // Add updated pair to the queue
+                    ArrayList<Integer> temp = new ArrayList<>();
+                    temp.add(dist[v]);
+                    temp.add(v);
+                    pq.offer(temp);
+                }
+            }
+        }
+
+        // Return the shortest distance array
+        return dist;
+    }
+
+    // Driver program to test methods of graph class
+    public static void main(String[] args) {
+        int V = 5;      
+        int src = 0;    
+
+        // Edge list format: {u, v, weight}
+        int[][] edges = {
+            {0, 1, 4}, {0, 2, 8}, {1, 4, 6},
+            {2, 3, 2}, {3, 4, 10}
+        };
+
+        // Get shortest path distances
+        int[] result = dijkstra(V, edges, src);
+
+        // Print shortest distances in one line
+        for (int d : result)
+            System.out.print(d + " ");
+    }
+}