mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-13 18:00:18 +08:00
translation: Add Python and Java code for EN version (#1345)
* Add the intial translation of code of all the languages * test * revert * Remove * Add Python and Java code for EN version
This commit is contained in:
117
en/codes/java/chapter_graph/graph_adjacency_list.java
Normal file
117
en/codes/java/chapter_graph/graph_adjacency_list.java
Normal file
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* File: graph_adjacency_list.java
|
||||
* Created Time: 2023-01-26
|
||||
* Author: krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
package chapter_graph;
|
||||
|
||||
import java.util.*;
|
||||
import utils.*;
|
||||
|
||||
/* Undirected graph class based on adjacency list */
|
||||
class GraphAdjList {
|
||||
// Adjacency list, key: vertex, value: all adjacent vertices of that vertex
|
||||
Map<Vertex, List<Vertex>> adjList;
|
||||
|
||||
/* Constructor */
|
||||
public GraphAdjList(Vertex[][] edges) {
|
||||
this.adjList = new HashMap<>();
|
||||
// Add all vertices and edges
|
||||
for (Vertex[] edge : edges) {
|
||||
addVertex(edge[0]);
|
||||
addVertex(edge[1]);
|
||||
addEdge(edge[0], edge[1]);
|
||||
}
|
||||
}
|
||||
|
||||
/* Get the number of vertices */
|
||||
public int size() {
|
||||
return adjList.size();
|
||||
}
|
||||
|
||||
/* Add edge */
|
||||
public void addEdge(Vertex vet1, Vertex vet2) {
|
||||
if (!adjList.containsKey(vet1) || !adjList.containsKey(vet2) || vet1 == vet2)
|
||||
throw new IllegalArgumentException();
|
||||
// Add edge vet1 - vet2
|
||||
adjList.get(vet1).add(vet2);
|
||||
adjList.get(vet2).add(vet1);
|
||||
}
|
||||
|
||||
/* Remove edge */
|
||||
public void removeEdge(Vertex vet1, Vertex vet2) {
|
||||
if (!adjList.containsKey(vet1) || !adjList.containsKey(vet2) || vet1 == vet2)
|
||||
throw new IllegalArgumentException();
|
||||
// Remove edge vet1 - vet2
|
||||
adjList.get(vet1).remove(vet2);
|
||||
adjList.get(vet2).remove(vet1);
|
||||
}
|
||||
|
||||
/* Add vertex */
|
||||
public void addVertex(Vertex vet) {
|
||||
if (adjList.containsKey(vet))
|
||||
return;
|
||||
// Add a new linked list to the adjacency list
|
||||
adjList.put(vet, new ArrayList<>());
|
||||
}
|
||||
|
||||
/* Remove vertex */
|
||||
public void removeVertex(Vertex vet) {
|
||||
if (!adjList.containsKey(vet))
|
||||
throw new IllegalArgumentException();
|
||||
// Remove the vertex vet's corresponding linked list from the adjacency list
|
||||
adjList.remove(vet);
|
||||
// Traverse other vertices' linked lists, removing all edges containing vet
|
||||
for (List<Vertex> list : adjList.values()) {
|
||||
list.remove(vet);
|
||||
}
|
||||
}
|
||||
|
||||
/* Print the adjacency list */
|
||||
public void print() {
|
||||
System.out.println("Adjacency list =");
|
||||
for (Map.Entry<Vertex, List<Vertex>> pair : adjList.entrySet()) {
|
||||
List<Integer> tmp = new ArrayList<>();
|
||||
for (Vertex vertex : pair.getValue())
|
||||
tmp.add(vertex.val);
|
||||
System.out.println(pair.getKey().val + ": " + tmp + ",");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class graph_adjacency_list {
|
||||
public static void main(String[] args) {
|
||||
/* Initialize undirected graph */
|
||||
Vertex[] v = Vertex.valsToVets(new int[] { 1, 3, 2, 5, 4 });
|
||||
Vertex[][] edges = { { v[0], v[1] }, { v[0], v[3] }, { v[1], v[2] },
|
||||
{ v[2], v[3] }, { v[2], v[4] }, { v[3], v[4] } };
|
||||
GraphAdjList graph = new GraphAdjList(edges);
|
||||
System.out.println("\nAfter initialization, the graph is");
|
||||
graph.print();
|
||||
|
||||
/* Add edge */
|
||||
// Vertices 1, 2 i.e., v[0], v[2]
|
||||
graph.addEdge(v[0], v[2]);
|
||||
System.out.println("\nAfter adding edge 1-2, the graph is");
|
||||
graph.print();
|
||||
|
||||
/* Remove edge */
|
||||
// Vertices 1, 3 i.e., v[0], v[1]
|
||||
graph.removeEdge(v[0], v[1]);
|
||||
System.out.println("\nAfter removing edge 1-3, the graph is");
|
||||
graph.print();
|
||||
|
||||
/* Add vertex */
|
||||
Vertex v5 = new Vertex(6);
|
||||
graph.addVertex(v5);
|
||||
System.out.println("\nAfter adding vertex 6, the graph is");
|
||||
graph.print();
|
||||
|
||||
/* Remove vertex */
|
||||
// Vertex 3 i.e., v[1]
|
||||
graph.removeVertex(v[1]);
|
||||
System.out.println("\nAfter removing vertex 3, the graph is");
|
||||
graph.print();
|
||||
}
|
||||
}
|
||||
131
en/codes/java/chapter_graph/graph_adjacency_matrix.java
Normal file
131
en/codes/java/chapter_graph/graph_adjacency_matrix.java
Normal file
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* File: graph_adjacency_matrix.java
|
||||
* Created Time: 2023-01-26
|
||||
* Author: krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
package chapter_graph;
|
||||
|
||||
import utils.*;
|
||||
import java.util.*;
|
||||
|
||||
/* Undirected graph class based on adjacency matrix */
|
||||
class GraphAdjMat {
|
||||
List<Integer> vertices; // Vertex list, elements represent "vertex value", index represents "vertex index"
|
||||
List<List<Integer>> adjMat; // Adjacency matrix, row and column indices correspond to "vertex index"
|
||||
|
||||
/* Constructor */
|
||||
public GraphAdjMat(int[] vertices, int[][] edges) {
|
||||
this.vertices = new ArrayList<>();
|
||||
this.adjMat = new ArrayList<>();
|
||||
// Add vertex
|
||||
for (int val : vertices) {
|
||||
addVertex(val);
|
||||
}
|
||||
// Add edge
|
||||
// Please note, edges elements represent vertex indices, corresponding to vertices elements indices
|
||||
for (int[] e : edges) {
|
||||
addEdge(e[0], e[1]);
|
||||
}
|
||||
}
|
||||
|
||||
/* Get the number of vertices */
|
||||
public int size() {
|
||||
return vertices.size();
|
||||
}
|
||||
|
||||
/* Add vertex */
|
||||
public void addVertex(int val) {
|
||||
int n = size();
|
||||
// Add new vertex value to the vertex list
|
||||
vertices.add(val);
|
||||
// Add a row to the adjacency matrix
|
||||
List<Integer> newRow = new ArrayList<>(n);
|
||||
for (int j = 0; j < n; j++) {
|
||||
newRow.add(0);
|
||||
}
|
||||
adjMat.add(newRow);
|
||||
// Add a column to the adjacency matrix
|
||||
for (List<Integer> row : adjMat) {
|
||||
row.add(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Remove vertex */
|
||||
public void removeVertex(int index) {
|
||||
if (index >= size())
|
||||
throw new IndexOutOfBoundsException();
|
||||
// Remove vertex at `index` from the vertex list
|
||||
vertices.remove(index);
|
||||
// Remove the row at `index` from the adjacency matrix
|
||||
adjMat.remove(index);
|
||||
// Remove the column at `index` from the adjacency matrix
|
||||
for (List<Integer> row : adjMat) {
|
||||
row.remove(index);
|
||||
}
|
||||
}
|
||||
|
||||
/* Add edge */
|
||||
// Parameters i, j correspond to vertices element indices
|
||||
public void addEdge(int i, int j) {
|
||||
// Handle index out of bounds and equality
|
||||
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j)
|
||||
throw new IndexOutOfBoundsException();
|
||||
// In an undirected graph, the adjacency matrix is symmetric about the main diagonal, i.e., satisfies (i, j) == (j, i)
|
||||
adjMat.get(i).set(j, 1);
|
||||
adjMat.get(j).set(i, 1);
|
||||
}
|
||||
|
||||
/* Remove edge */
|
||||
// Parameters i, j correspond to vertices element indices
|
||||
public void removeEdge(int i, int j) {
|
||||
// Handle index out of bounds and equality
|
||||
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j)
|
||||
throw new IndexOutOfBoundsException();
|
||||
adjMat.get(i).set(j, 0);
|
||||
adjMat.get(j).set(i, 0);
|
||||
}
|
||||
|
||||
/* Print adjacency matrix */
|
||||
public void print() {
|
||||
System.out.print("Vertex list = ");
|
||||
System.out.println(vertices);
|
||||
System.out.println("Adjacency matrix =");
|
||||
PrintUtil.printMatrix(adjMat);
|
||||
}
|
||||
}
|
||||
|
||||
public class graph_adjacency_matrix {
|
||||
public static void main(String[] args) {
|
||||
/* Initialize undirected graph */
|
||||
// Please note, edges elements represent vertex indices, corresponding to vertices elements indices
|
||||
int[] vertices = { 1, 3, 2, 5, 4 };
|
||||
int[][] edges = { { 0, 1 }, { 0, 3 }, { 1, 2 }, { 2, 3 }, { 2, 4 }, { 3, 4 } };
|
||||
GraphAdjMat graph = new GraphAdjMat(vertices, edges);
|
||||
System.out.println("\nAfter initialization, the graph is");
|
||||
graph.print();
|
||||
|
||||
/* Add edge */
|
||||
// Indices of vertices 1, 2 are 0, 2 respectively
|
||||
graph.addEdge(0, 2);
|
||||
System.out.println("\nAfter adding edge 1-2, the graph is");
|
||||
graph.print();
|
||||
|
||||
/* Remove edge */
|
||||
// Indices of vertices 1, 3 are 0, 1 respectively
|
||||
graph.removeEdge(0, 1);
|
||||
System.out.println("\nAfter removing edge 1-3, the graph is");
|
||||
graph.print();
|
||||
|
||||
/* Add vertex */
|
||||
graph.addVertex(6);
|
||||
System.out.println("\nAfter adding vertex 6, the graph is");
|
||||
graph.print();
|
||||
|
||||
/* Remove vertex */
|
||||
// Index of vertex 3 is 1
|
||||
graph.removeVertex(1);
|
||||
System.out.println("\nAfter removing vertex 3, the graph is");
|
||||
graph.print();
|
||||
}
|
||||
}
|
||||
55
en/codes/java/chapter_graph/graph_bfs.java
Normal file
55
en/codes/java/chapter_graph/graph_bfs.java
Normal file
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* File: graph_bfs.java
|
||||
* Created Time: 2023-02-12
|
||||
* Author: krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
package chapter_graph;
|
||||
|
||||
import java.util.*;
|
||||
import utils.*;
|
||||
|
||||
public class graph_bfs {
|
||||
/* Breadth-first traversal */
|
||||
// Use adjacency list to represent the graph, to obtain all adjacent vertices of a specified vertex
|
||||
static List<Vertex> graphBFS(GraphAdjList graph, Vertex startVet) {
|
||||
// Vertex traversal sequence
|
||||
List<Vertex> res = new ArrayList<>();
|
||||
// Hash set, used to record visited vertices
|
||||
Set<Vertex> visited = new HashSet<>();
|
||||
visited.add(startVet);
|
||||
// Queue used to implement BFS
|
||||
Queue<Vertex> que = new LinkedList<>();
|
||||
que.offer(startVet);
|
||||
// Starting from vertex vet, loop until all vertices are visited
|
||||
while (!que.isEmpty()) {
|
||||
Vertex vet = que.poll(); // Dequeue the vertex at the head of the queue
|
||||
res.add(vet); // Record visited vertex
|
||||
// Traverse all adjacent vertices of that vertex
|
||||
for (Vertex adjVet : graph.adjList.get(vet)) {
|
||||
if (visited.contains(adjVet))
|
||||
continue; // Skip already visited vertices
|
||||
que.offer(adjVet); // Only enqueue unvisited vertices
|
||||
visited.add(adjVet); // Mark the vertex as visited
|
||||
}
|
||||
}
|
||||
// Return the vertex traversal sequence
|
||||
return res;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
/* Initialize undirected graph */
|
||||
Vertex[] v = Vertex.valsToVets(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
|
||||
Vertex[][] edges = { { v[0], v[1] }, { v[0], v[3] }, { v[1], v[2] }, { v[1], v[4] },
|
||||
{ v[2], v[5] }, { v[3], v[4] }, { v[3], v[6] }, { v[4], v[5] },
|
||||
{ v[4], v[7] }, { v[5], v[8] }, { v[6], v[7] }, { v[7], v[8] } };
|
||||
GraphAdjList graph = new GraphAdjList(edges);
|
||||
System.out.println("\nAfter initialization, the graph is");
|
||||
graph.print();
|
||||
|
||||
/* Breadth-first traversal */
|
||||
List<Vertex> res = graphBFS(graph, v[0]);
|
||||
System.out.println("\nBreadth-first traversal (BFS) vertex sequence is");
|
||||
System.out.println(Vertex.vetsToVals(res));
|
||||
}
|
||||
}
|
||||
51
en/codes/java/chapter_graph/graph_dfs.java
Normal file
51
en/codes/java/chapter_graph/graph_dfs.java
Normal file
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: graph_dfs.java
|
||||
* Created Time: 2023-02-12
|
||||
* Author: krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
package chapter_graph;
|
||||
|
||||
import java.util.*;
|
||||
import utils.*;
|
||||
|
||||
public class graph_dfs {
|
||||
/* Depth-first traversal helper function */
|
||||
static void dfs(GraphAdjList graph, Set<Vertex> visited, List<Vertex> res, Vertex vet) {
|
||||
res.add(vet); // Record visited vertex
|
||||
visited.add(vet); // Mark the vertex as visited
|
||||
// Traverse all adjacent vertices of that vertex
|
||||
for (Vertex adjVet : graph.adjList.get(vet)) {
|
||||
if (visited.contains(adjVet))
|
||||
continue; // Skip already visited vertices
|
||||
// Recursively visit adjacent vertices
|
||||
dfs(graph, visited, res, adjVet);
|
||||
}
|
||||
}
|
||||
|
||||
/* Depth-first traversal */
|
||||
// Use adjacency list to represent the graph, to obtain all adjacent vertices of a specified vertex
|
||||
static List<Vertex> graphDFS(GraphAdjList graph, Vertex startVet) {
|
||||
// Vertex traversal sequence
|
||||
List<Vertex> res = new ArrayList<>();
|
||||
// Hash set, used to record visited vertices
|
||||
Set<Vertex> visited = new HashSet<>();
|
||||
dfs(graph, visited, res, startVet);
|
||||
return res;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
/* Initialize undirected graph */
|
||||
Vertex[] v = Vertex.valsToVets(new int[] { 0, 1, 2, 3, 4, 5, 6 });
|
||||
Vertex[][] edges = { { v[0], v[1] }, { v[0], v[3] }, { v[1], v[2] },
|
||||
{ v[2], v[5] }, { v[4], v[5] }, { v[5], v[6] } };
|
||||
GraphAdjList graph = new GraphAdjList(edges);
|
||||
System.out.println("\nAfter initialization, the graph is");
|
||||
graph.print();
|
||||
|
||||
/* Depth-first traversal */
|
||||
List<Vertex> res = graphDFS(graph, v[0]);
|
||||
System.out.println("\nDepth-first traversal (DFS) vertex sequence is");
|
||||
System.out.println(Vertex.vetsToVals(res));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user