Sei sulla pagina 1di 3

package dismatLab2;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class DismatLab2 {

public static void main(String[] args) {

if(args.length != 1) {
System.out.println("Neispravan broj argumenata!");
return;
}

Path file = Paths.get(args[0]);


String string = extractData(file);

Scanner sc = new Scanner(string);


int n = sc.nextInt();
int[][] matrix = new int[n][n];
extractMatrix(sc, matrix, n);
sc.close();

List<Node> nodes = new LinkedList<Node>();

fillListFromMatrix(nodes, matrix);

findMaxCycle(nodes, matrix[0].length);

System.out.println(max);

public static String extractData(Path file) {


try {
return Files.readString(file);
} catch(IOException e) {
e.printStackTrace();
System.out.println("Greška u otvaranju datoteke!");
System.exit(1);
return null;
}
}

public static void extractMatrix(Scanner sc, int[][] matrix, int n) {


int i = 0;
while(i < n) {
int j = 0;
while(sc.hasNext() && j < n) {
if(sc.hasNextInt()) {
matrix[i][j] = sc.nextInt();
j++;
} else {
sc.next();
}
}
i++;
}
}

public static class Node { //Čvor


String name;
List<Node> linkedNodes = new LinkedList<Node>();

int childrenNum = 0;

boolean checked = false;


boolean origin = false;

@Override
public String toString() {
return name;
}

public static void fillListFromMatrix(List<Node> nodes, int[][] matrix) {


for(int i = 0; i < matrix[0].length; i++) {
nodes.add(new Node()); //Dodavanje n čvorova n*n matrice
nodes.get(i).name = "N" + Integer.toString(i);
}
for(int j = 0; j < matrix[0].length; j++) {
for(int k = 0; k < matrix[0].length; k++) {
if(matrix[j][k] == 1) {
nodes.get(j).linkedNodes.add(nodes.get(k)); //Stvaraj
povezanost između čvorova
nodes.get(j).childrenNum++;
}
}
}

public static void findMaxCycle(List<Node> nodes, int len) {


for(int pos = 0; pos < len; pos++) {
nodes.get(pos).origin = true;
startingFunction(nodes.get(pos), len, 0);
nodes.get(pos).origin = false;
}

public static void startingFunction(Node origin, int len, int localStep) {

int repetition = origin.childrenNum;


if(repetition == 0) return;

for(int i = 0; i < repetition; i++) {


recursiveFunction(origin.linkedNodes.get(i), len, 1);
}

}
public static void recursiveFunction(Node node, int len, int localStep) {

if(localStep > len) { //Ako smo prešli više od n-koraka


return;
}

if(node.origin == true && localStep > 2) { //Ako smo kojim slučajem


došli do ishodišta
if(localStep > max) max = localStep;
return;
}

node.checked = true;

int repetition = node.childrenNum;


if(repetition == 0) {
return;
}

for(int i = 0; i < repetition; i++) {


if(node.linkedNodes.get(i).checked == false) {
recursiveFunction(node.linkedNodes.get(i), len, localStep +
1);
}
}

node.checked = false;

public static int max = 0;

//5, 4, 0, 0, 3, 8, 0, 5, 10

Potrebbero piacerti anche