├── .gitignore ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── graph ├── build.gradle ├── settings.gradle └── src │ └── main │ └── java │ └── com │ └── mindorks │ └── java │ └── graph │ ├── core │ ├── DirectedGraph.java │ ├── EGraph.java │ ├── Edge.java │ ├── EdgeWeightedGraph.java │ ├── Graph.java │ ├── KruskalMST.java │ ├── MST.java │ └── UndirectedGraph.java │ └── utils │ ├── Bag.java │ ├── BreathFirstPaths.java │ ├── DepthFirstPaths.java │ ├── Paths.java │ ├── QuickUnionUF.java │ └── UF.java ├── settings.gradle └── src └── main └── java └── Demo.java /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | .gradle 3 | .idea 4 | out -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Graph Java Library 2 | 3 | Graph Data Structure and Algorithms. 4 | 5 | ### License 6 | ``` 7 | Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 8 | 9 | Licensed under the Apache License, Version 2.0 (the "License"); 10 | you may not use this file except in compliance with the License. 11 | You may obtain a copy of the License at 12 | 13 | http://www.apache.org/licenses/LICENSE-2.0 14 | 15 | Unless required by applicable law or agreed to in writing, software 16 | distributed under the License is distributed on an "AS IS" BASIS, 17 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | See the License for the specific language governing permissions and 19 | limitations under the License 20 | ``` -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | group 'com.mindorks' 18 | version '1.0-SNAPSHOT' 19 | 20 | apply plugin: 'java' 21 | 22 | sourceCompatibility = 1.8 23 | 24 | repositories { 25 | mavenCentral() 26 | } 27 | 28 | jar { 29 | manifest { 30 | attributes( 31 | 'Main-Class': 'Demo' 32 | ) 33 | } 34 | } 35 | 36 | dependencies { 37 | compile project(':graph') 38 | testCompile group: 'junit', name: 'junit', version: '4.12' 39 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/janishar/graph-library/db4b2a7a0797d5ce88ce8fcb607b8b4cb28b6aaf/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.2.1-bin.zip 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /graph/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | group 'com.mindorks.java' 18 | version '1.0-SNAPSHOT' 19 | 20 | apply plugin: 'java' 21 | apply plugin: 'idea' 22 | 23 | sourceCompatibility = 1.8 24 | 25 | repositories { 26 | mavenCentral() 27 | } 28 | 29 | dependencies { 30 | testCompile group: 'junit', name: 'junit', version: '4.12' 31 | } 32 | -------------------------------------------------------------------------------- /graph/settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | rootProject.name = 'graph' 18 | 19 | -------------------------------------------------------------------------------- /graph/src/main/java/com/mindorks/java/graph/core/DirectedGraph.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | package com.mindorks.java.graph.core; 18 | 19 | public class DirectedGraph extends UndirectedGraph { 20 | 21 | public DirectedGraph(int V) { 22 | super(V); 23 | } 24 | 25 | /** 26 | * add edge v -> w 27 | */ 28 | @Override 29 | public void addEdge(int v, int w) { 30 | getAdjArray()[v].add(w); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /graph/src/main/java/com/mindorks/java/graph/core/EGraph.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | package com.mindorks.java.graph.core; 18 | 19 | public interface EGraph { 20 | 21 | void addEdge(Edge e); 22 | 23 | Iterable adj(int v); 24 | 25 | Iterable edges(); 26 | 27 | int V(); 28 | 29 | int E(); 30 | } 31 | -------------------------------------------------------------------------------- /graph/src/main/java/com/mindorks/java/graph/core/Edge.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | package com.mindorks.java.graph.core; 18 | 19 | public class Edge implements Comparable { 20 | 21 | private final int v, w; 22 | private final double weight; 23 | 24 | public Edge(int v, int w, double weight) { 25 | this.v = v; 26 | this.w = w; 27 | this.weight = weight; 28 | } 29 | 30 | public int either() { 31 | return v; 32 | } 33 | 34 | public int other(int vertex) { 35 | if (vertex == v) return w; 36 | return v; 37 | } 38 | 39 | public double weight() { 40 | return weight; 41 | } 42 | 43 | @Override 44 | public int compareTo(Edge that) { 45 | if (this.weight < that.weight) return -1; 46 | if (this.weight == that.weight) return 0; 47 | return 1; 48 | } 49 | 50 | @Override 51 | public String toString() { 52 | return "Edge{" + 53 | "v=" + v + 54 | ", w=" + w + 55 | ", weight=" + weight + 56 | '}'; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /graph/src/main/java/com/mindorks/java/graph/core/EdgeWeightedGraph.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | package com.mindorks.java.graph.core; 18 | 19 | import java.util.Arrays; 20 | import java.util.LinkedList; 21 | import java.util.Stack; 22 | 23 | public class EdgeWeightedGraph implements EGraph { 24 | 25 | private final int V; 26 | private final LinkedList[] adj; 27 | 28 | @SuppressWarnings("unchecked") 29 | public EdgeWeightedGraph(int V) { 30 | this.V = V; 31 | adj = (LinkedList[]) new LinkedList[V]; 32 | for (int v = 0; v < V; v++) 33 | adj[v] = new LinkedList<>(); 34 | } 35 | 36 | @Override 37 | public void addEdge(Edge e) { 38 | int v = e.either(); 39 | int w = e.other(v); 40 | adj[v].add(e); 41 | adj[w].add(e); 42 | } 43 | 44 | @Override 45 | public Iterable adj(int v) { 46 | return adj[v]; 47 | } 48 | 49 | @Override 50 | public Iterable edges() { 51 | Stack stack = new Stack<>(); 52 | for (int v = 0; v < V; v++) 53 | for (Edge e : adj[v]) 54 | stack.push(e); 55 | return stack; 56 | } 57 | 58 | @Override 59 | public int V() { 60 | return V; 61 | } 62 | 63 | @Override 64 | public int E() { 65 | return 0; 66 | } 67 | 68 | @Override 69 | public String toString() { 70 | return "EdgeWeightedGraph{" + 71 | "V=" + V + 72 | ", adj=" + Arrays.toString(adj) + 73 | '}'; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /graph/src/main/java/com/mindorks/java/graph/core/Graph.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | package com.mindorks.java.graph.core; 18 | 19 | public interface Graph { 20 | 21 | /** 22 | * prints all the edges of the graph 23 | */ 24 | static void print(Graph G) { 25 | for (int v = 0; v < G.V(); v++) { 26 | for (int w : G.adj(v)) { 27 | System.out.println(v + "-" + w); 28 | } 29 | } 30 | } 31 | 32 | /** 33 | * @return number of edges connected to the vertex v 34 | */ 35 | static int degree(Graph G, int v) { 36 | int degree = 0; 37 | for (int w : G.adj(v)) degree++; 38 | return degree; 39 | } 40 | 41 | static int maxDegree(Graph G) { 42 | int max = 0; 43 | for (int v = 0; v < G.V(); ) { 44 | int degree = degree(G, v); 45 | if (max < degree) max = degree; 46 | } 47 | return max; 48 | } 49 | 50 | static double averageDegree(Graph G) { 51 | return 2.0 * G.E() / G.V(); // each edge is counted twice v-w and w-v 52 | } 53 | 54 | static int numberOfSelfLoops(Graph G) { 55 | int count = 0; 56 | for (int v = 0; v < G.V(); v++) 57 | for (int w : G.adj(v)) 58 | if (v == w) count++; 59 | return count / 2; //each edge is counted twice 60 | } 61 | 62 | /** 63 | * Add an edge v-w 64 | */ 65 | void addEdge(int v, int w); 66 | 67 | /** 68 | * @return vertices adjacent to v 69 | */ 70 | Iterable adj(int v); 71 | 72 | /** 73 | * @return Number of vertices 74 | */ 75 | int V(); 76 | 77 | /** 78 | * @return number of edges 79 | */ 80 | int E(); 81 | 82 | } 83 | -------------------------------------------------------------------------------- /graph/src/main/java/com/mindorks/java/graph/core/KruskalMST.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | package com.mindorks.java.graph.core; 18 | 19 | import com.mindorks.java.graph.utils.QuickUnionUF; 20 | import com.mindorks.java.graph.utils.UF; 21 | 22 | import java.util.PriorityQueue; 23 | import java.util.Queue; 24 | import java.util.concurrent.LinkedBlockingQueue; 25 | 26 | public class KruskalMST implements MST { 27 | 28 | private Queue mst = new LinkedBlockingQueue<>(); 29 | 30 | public KruskalMST(EGraph G) { 31 | PriorityQueue pq = new PriorityQueue<>();// minimum priority queue 32 | for (Edge e : G.edges()) 33 | pq.add(e); 34 | 35 | UF uf = new QuickUnionUF(G.V()); 36 | while (!pq.isEmpty() && mst.size() < G.V() - 1) { 37 | Edge e = pq.poll(); 38 | int v = e.either(); 39 | int w = e.other(v); 40 | if (!uf.connected(v, w)) { //to check cyclic components or duplicate edges 41 | uf.union(v, w); 42 | mst.add(e); 43 | } 44 | } 45 | } 46 | 47 | @Override 48 | public Iterable edges() { 49 | return mst; 50 | } 51 | 52 | @Override 53 | public double weight() { 54 | double weight = 0; 55 | for (Edge e : mst) 56 | weight += e.weight(); 57 | return weight; 58 | } 59 | 60 | @Override 61 | public String toString() { 62 | return "KruskalMST{" + 63 | "mst=" + mst + 64 | '}'; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /graph/src/main/java/com/mindorks/java/graph/core/MST.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | package com.mindorks.java.graph.core; 18 | 19 | /** 20 | * Minimum Spanning Tree: 21 | * Three having all the vertices of an edge weighted graph 22 | * such that the edges give the minimum weight of the tree 23 | */ 24 | public interface MST { 25 | 26 | Iterable edges(); 27 | 28 | double weight(); 29 | } 30 | -------------------------------------------------------------------------------- /graph/src/main/java/com/mindorks/java/graph/core/UndirectedGraph.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | package com.mindorks.java.graph.core; 18 | 19 | import java.util.LinkedList; 20 | 21 | public class UndirectedGraph implements Graph { 22 | 23 | // number of vertices 24 | private final int V; 25 | 26 | /** 27 | * adjacency list implementation of data representation. 28 | * The adjacency matrix hold the vertices by index 29 | * and it connected vertex list 30 | */ 31 | private LinkedList[] adj; 32 | 33 | 34 | @SuppressWarnings("unchecked") 35 | public UndirectedGraph(int V) { 36 | this.V = V; 37 | adj = (LinkedList[]) new LinkedList[V]; // array of Generic List has to be cast; 38 | for (int v = 0; v < V; v++) 39 | adj[v] = new LinkedList<>(); 40 | } 41 | 42 | @Override 43 | public void addEdge(int v, int w) { 44 | adj[v].add(w); 45 | adj[w].add(v); 46 | } 47 | 48 | @Override 49 | public Iterable adj(int v) { 50 | return adj[v]; 51 | } 52 | 53 | @Override 54 | public int V() { 55 | return V; 56 | } 57 | 58 | @Override 59 | public int E() { 60 | return 0; 61 | } 62 | 63 | protected LinkedList[] getAdjArray() { 64 | return adj; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /graph/src/main/java/com/mindorks/java/graph/utils/Bag.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | package com.mindorks.java.graph.utils; 18 | 19 | import java.util.Iterator; 20 | 21 | /** 22 | * Created by janisharali on 26/10/17. 23 | */ 24 | public class Bag implements Iterable { 25 | 26 | private Node start; 27 | 28 | public void put(T t) { 29 | Node node = new Node(t); 30 | if (start != null) { 31 | Node oldStart = start; 32 | start = node; 33 | start.next = oldStart; 34 | } else { 35 | start = node; 36 | } 37 | } 38 | 39 | public T get() { 40 | if (start == null) 41 | return null; 42 | Node current = start; 43 | start = current.next; 44 | return current.value; 45 | } 46 | 47 | public T remove(T t) { 48 | Node current = start; 49 | Node previous = null; 50 | 51 | while (current != null) { 52 | if (current.value.equals(t)) { 53 | if (previous == null) { 54 | start = null; 55 | } else { 56 | previous.next = current.next; 57 | current = current.next; 58 | } 59 | } else { 60 | previous = current; 61 | current = current.next; 62 | } 63 | } 64 | 65 | T value = null; 66 | if (previous != null) { 67 | value = previous.value; 68 | } 69 | 70 | return value; 71 | } 72 | 73 | @Override 74 | public Iterator iterator() { 75 | return new BagIterator(); 76 | } 77 | 78 | private class Node { 79 | T value; 80 | Node next; 81 | 82 | Node(T value) { 83 | this.value = value; 84 | } 85 | } 86 | 87 | private class BagIterator implements Iterator { 88 | 89 | Node current; 90 | 91 | BagIterator() { 92 | current = start; 93 | } 94 | 95 | @Override 96 | public boolean hasNext() { 97 | return current != null; 98 | } 99 | 100 | @Override 101 | public T next() { 102 | T value = current.value; 103 | current = current.next; 104 | return value; 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /graph/src/main/java/com/mindorks/java/graph/utils/BreathFirstPaths.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | package com.mindorks.java.graph.utils; 18 | 19 | import com.mindorks.java.graph.core.Graph; 20 | 21 | import java.util.Queue; 22 | import java.util.concurrent.LinkedBlockingQueue; 23 | 24 | public class BreathFirstPaths extends Paths { 25 | 26 | public BreathFirstPaths(Graph G, int s) { 27 | super(G, s); 28 | bfs(G, s); 29 | } 30 | 31 | private void bfs(Graph G, int s) { 32 | Queue q = new LinkedBlockingQueue<>(); 33 | q.add(s); 34 | marked[s] = true; 35 | while (!q.isEmpty()) { 36 | int v = q.poll(); 37 | for (int w : G.adj(v)) 38 | if (!marked[w]) { 39 | q.add(w); 40 | marked[w] = true; 41 | edgeTo[w] = v; 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /graph/src/main/java/com/mindorks/java/graph/utils/DepthFirstPaths.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | package com.mindorks.java.graph.utils; 18 | 19 | import com.mindorks.java.graph.core.Graph; 20 | 21 | public class DepthFirstPaths extends Paths { 22 | 23 | public DepthFirstPaths(Graph G, int s) { 24 | super(G, s); 25 | dfs(G, s); 26 | } 27 | 28 | private void dfs(Graph G, int v) { 29 | marked[v] = true; 30 | for (int w : G.adj(v)) 31 | if (!marked[w]) { 32 | dfs(G, w); 33 | edgeTo[w] = v; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /graph/src/main/java/com/mindorks/java/graph/utils/Paths.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | package com.mindorks.java.graph.utils; 18 | 19 | import com.mindorks.java.graph.core.Graph; 20 | 21 | import java.util.Stack; 22 | 23 | public abstract class Paths { 24 | 25 | protected final Graph G; 26 | protected final int s; //source vertex 27 | protected boolean[] marked; 28 | protected int[] edgeTo; 29 | 30 | public Paths(Graph G, int s) { 31 | this.G = G; 32 | this.s = s; 33 | marked = new boolean[G.V()]; 34 | edgeTo = new int[G.V()]; 35 | } 36 | 37 | /** 38 | * Finds if there is a path from s to v 39 | */ 40 | public boolean hasPathTo(int v) { 41 | return marked[v]; //if marked then it lies in the traversal 42 | } 43 | 44 | /** 45 | * path from s to v : null if no such path 46 | */ 47 | public Iterable pathTo(int v) { 48 | if (!hasPathTo(v)) return null; 49 | Stack path = new Stack<>(); 50 | for (int x = v; x != s; x = edgeTo[x]) 51 | path.push(x); 52 | path.push(s); 53 | return path; 54 | } 55 | 56 | public void printConnectedVertices() { 57 | for (int v = 0; v < G.V(); v++) 58 | if (hasPathTo(v)) 59 | System.out.println(v); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /graph/src/main/java/com/mindorks/java/graph/utils/QuickUnionUF.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | package com.mindorks.java.graph.utils; 18 | 19 | import java.util.Arrays; 20 | 21 | public class QuickUnionUF implements UF { 22 | 23 | // stores the parent id of each node 24 | private int[] id; 25 | // stores the size of the component 26 | private int[] sz; 27 | 28 | public QuickUnionUF(int N) { 29 | id = new int[N]; 30 | sz = new int[N]; 31 | for (int i = 0; i < N; i++) { 32 | id[i] = i; 33 | sz[i] = 1; 34 | } 35 | } 36 | 37 | private int root(int i) { 38 | while (i != id[i]) { 39 | id[i] = id[id[i]]; //path compression: grandparent to be stored as the parent. 40 | i = id[i]; 41 | } 42 | return i; 43 | } 44 | 45 | /** 46 | * attach p's root to q's root 47 | */ 48 | @Override 49 | public void union(int p, int q) { 50 | int i = root(p); 51 | int j = root(q); 52 | if (i == j) return; // already in the same component 53 | if (sz[i] < sz[j]) { 54 | id[i] = j; //merging smaller tree to a larger tree 55 | sz[j] += sz[i]; 56 | } else { 57 | id[j] = i; 58 | sz[i] += sz[j]; 59 | } 60 | } 61 | 62 | @Override 63 | public boolean connected(int p, int q) { 64 | return root(p) == root(q); 65 | } 66 | 67 | @Override 68 | public int find(int p) { 69 | return root(p); 70 | } 71 | 72 | @Override 73 | public int count() { 74 | return 0; 75 | } 76 | 77 | @Override 78 | public String toString() { 79 | return "QuickUnionUF{" + 80 | "id=" + Arrays.toString(id) + 81 | ", sz=" + Arrays.toString(sz) + 82 | '}'; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /graph/src/main/java/com/mindorks/java/graph/utils/UF.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | package com.mindorks.java.graph.utils; 18 | 19 | public interface UF { 20 | 21 | /** 22 | * Add component between p and q 23 | */ 24 | void union(int p, int q); 25 | 26 | /** 27 | * check if p and q are in the same component 28 | */ 29 | boolean connected(int p, int q); 30 | 31 | /** 32 | * component identifier for p 33 | */ 34 | int find(int p); 35 | 36 | /** 37 | * number of components 38 | */ 39 | int count(); 40 | 41 | } 42 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | rootProject.name = 'graph-library' 18 | include ':graph' -------------------------------------------------------------------------------- /src/main/java/Demo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License 15 | */ 16 | 17 | import com.mindorks.java.graph.core.*; 18 | import com.mindorks.java.graph.utils.*; 19 | 20 | /** 21 | * Created by janisharali on 26/10/17. 22 | */ 23 | public class Demo { 24 | 25 | public static void main(String[] args) { 26 | testGraph(); 27 | } 28 | 29 | public static void testGraph() { 30 | testBFS(getTestGraph()); 31 | } 32 | 33 | private static void testKruskalMST() { 34 | EGraph graph = new EdgeWeightedGraph(6); 35 | graph.addEdge(new Edge(0, 1, 0.21)); 36 | graph.addEdge(new Edge(1, 2, 0.11)); 37 | graph.addEdge(new Edge(2, 4, 0.93)); 38 | graph.addEdge(new Edge(1, 3, 0.76)); 39 | graph.addEdge(new Edge(3, 4, 0.40)); 40 | graph.addEdge(new Edge(1, 5, 0.50)); 41 | graph.addEdge(new Edge(0, 5, 0.97)); 42 | graph.addEdge(new Edge(5, 4, 0.38)); 43 | 44 | MST mst = new KruskalMST(graph); 45 | print(mst.edges()); 46 | print(mst.weight()); 47 | } 48 | 49 | private static void testUF() { 50 | UF uf = new QuickUnionUF(10); 51 | uf.union(4, 3); 52 | uf.union(3, 8); 53 | uf.union(6, 5); 54 | uf.union(9, 4); 55 | uf.union(2, 1); 56 | uf.union(5, 0); 57 | uf.union(7, 2); 58 | uf.union(6, 1); 59 | uf.union(7, 3); 60 | print(uf); 61 | } 62 | 63 | private static Graph getTestGraph() { 64 | Graph graph = new UndirectedGraph(7); 65 | graph.addEdge(0, 1); 66 | graph.addEdge(0, 2); 67 | graph.addEdge(0, 6); 68 | graph.addEdge(6, 4); 69 | graph.addEdge(4, 3); 70 | graph.addEdge(4, 5); 71 | graph.addEdge(5, 3); 72 | graph.addEdge(0, 5); 73 | return graph; 74 | } 75 | 76 | private static void testDFS(Graph graph) { 77 | Paths paths = new DepthFirstPaths(graph, 0); 78 | print(paths.pathTo(5)); 79 | } 80 | 81 | private static void testBFS(Graph graph) { 82 | BreathFirstPaths paths = new BreathFirstPaths(graph, 0); 83 | print(paths.pathTo(4));// will give the shortest path 84 | } 85 | 86 | private static void testBag() { 87 | Bag bag = new Bag<>(); 88 | bag.put("Janishar"); 89 | bag.put("Ali"); 90 | bag.put("Anwar"); 91 | bag.put("Anwar"); 92 | bag.put("is"); 93 | bag.put("awesome"); 94 | 95 | System.out.println(bag.get() + bag.get()); 96 | 97 | for (String item : bag) { 98 | System.out.println(item); 99 | } 100 | } 101 | 102 | private static void print(T t) { 103 | System.out.println(t); 104 | } 105 | } 106 | --------------------------------------------------------------------------------