Beginner coder checking if input is part of a cycle? - graph

public Graph (int nb){
this.nbNodes = nb;
this.adjacency = new boolean [nb][nb];
for (int i = 0; i < nb; i++){
for (int j = 0; j < nb; j++){
this.adjacency[i][j] = false;
}
}
}
public void addEdge (int i, int j){
if(!(i<0 || i>=this.nbNodes|| j<0 || j>=this.nbNodes))
{
this.adjacency[i][j] = true;
this.adjacency[j][i] = true;
}
}
public void removeEdge (int i, int j){
if(!(i<0 || i>=this.nbNodes|| j<0 || j>=this.nbNodes))
{
this.adjacency[i][j] = false;
this.adjacency[j][i] = false;
}
}
public int nbEdges(){
int c =0;
for(int i=0; i<this.nbNodes; i++)
{
for(int j= 0; j<this.nbNodes; j++)
{
if(this.adjacency[i][j]==true)
{
c++;
}
}
}
return c/2;
}
public boolean cycle(int start){
return false;
}
A Graph has a number of nodes nbNodes and is characterized by its adjacency matrix adjacency. adjacency[i][j] states whether or not there is an edge from the i-th node to the j-th node.
the graphs are undirected.
I am a beginner coder and am having trouble writing cycle(int start)
It takes as input an integer, g.cycle(i) returns true if the i-th node is part of a cycle (and false otherwise).
does anyone have any idea on how I should approach this?

Related

Leetcode 2360 Longest Cycle in a Graph

I use nearly the same method as in the discussion. But mine reaches the time limitation but his passes all cases. I want to know how to improve my code and why there is difference?
Here is my entire code:
boolean[] visited;
public int dfs(int step, int[] edges, int node, Map<Integer, Integer> path) {
path.put(node, step);
visited[node] = true;
if (edges[node] == -1) {
return -1;
}
if (path.containsKey(edges[node])) {
return step - path.get(edges[node]) + 1;
}
return dfs(step + 1, edges, edges[node], path);
}
public int longestCycle(int[] edges) {
int res = -1;
visited = new boolean[edges.length];
for (int i = 0; i < edges.length; i++) {
if (visited[i]) {
continue;
}
int maxCircleLength = dfs(0, edges, i, new HashMap<Integer, Integer>());
res = Math.max(maxCircleLength, res);
}
return res;
}
This is his solution:
public int longestCycle(int[] edges) {
int longest = -1;
boolean visited[] = new boolean[edges.length]; // global visisted
HashMap<Integer, Integer> map;
for(int i=0; i<edges.length; i++){
if(visited[i]) continue;
int distance = 0, curr_node = i;
map = new HashMap<>(); // local visited
while(curr_node != -1){
if(map.containsKey(curr_node)){
longest = Math.max(longest, distance - map.get(curr_node));
break;
}
if(visited[curr_node]) break;
visited[curr_node] = true;
map.put(curr_node, distance);
curr_node = edges[curr_node];
distance++;
}
}
return longest;
}

How create an adjacency matrix of a Maze graph

I'm working on making a maze Generator using Prim's Algorithm. I understand i have to make an undirected weighted graph and represent it on an Adjacency Matrix or List. i created the boolean[][] adjacenyMatrix array to show which edges currently exist in the maze. But i have an issue trying to implement the algorithm i thought of. Here is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter the size of the maze");
int mazeHeight = scanner.nextInt();
int mazeWidth = scanner.nextInt();
int noOfNodes = mazeHeight * mazeWidth;
boolean[][] adjacencyMatrix = new boolean[noOfNodes][noOfNodes];
for (int i = 0; i < mazeHeight; i++) {
for (int j = 0; j < mazeWidth; j++ ) {
// Edges exist from left to right
adjacencyMatrix[i][j] = true;
adjacencyMatrix[j][i] = true;
}
}
for (int i = 0; i < mazeWidth; i++) {
for (int j = 0; j < noOfNodes; j + mazeWidth) { // <-----------I'm having an issue here; Not a statement
// Edges exist from top to bottom
adjacencyMatrix[i][j] = true;
adjacencyMatrix[j][i] = true;
}
}
}
}
After taking a break; i looked over it and realised that i forgot to include the "=" symbol >.<
so j += mazeWidth

Update GridPane with Slider in JavaFx

I'm new at this, I´m creating a field that solves N x N Matrixes, and I want the spinner to add more TextFields every time I change its value, so the user can select the size of the matrix and then solve it...However I don't know how to do this.
I've tried to attach a listener JavaFX spinner but it didn't work, and it has created some errors in the code.
The code in question...
public static void main(String[] args) {
// TODO Auto-generated method stub
launch(args);
}
public void start(Stage primaryStage) throws Exception{
Double[][] A = new Double[6][6];
Label tamanoML = new Label("Tamaño Matriz:");
Spinner tamanoMS =new Spinner(1,5,0,1);
int tamano=(int) tamanoMS.getValue();
int r;
Label[] campoL = new Label[6];
TextField campo [][] = new TextField[6][6];
Button resolverB = new Button("Resolver matrix");
resolverB.setOnAction((ActionEvent t) -> {
int n=(int) tamanoMS.getValue();
int cont=0;
for(int i=0; i<n; i++) {
for(int j=0; j<n+1; j++) {
A[i][j]=Double.parseDouble(campo[i][j].getText());
}
}
for (int a = 0; a < n; a++) {
Double temp = 0.0;
temp = A[cont][cont];
for (int y = 0; y < (n + 1); y++) {
A[cont][y] = A[cont][y] / temp;
}
for (int x = 0; x < n; x++) {
if (x!=cont) {
Double c = A[x][cont];
for (int z = 0; z < (n + 1); z++) {
A[x][z] = ((-1 * c) * A[cont][z]) + A[x][z];
}
}
}
cont++;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n+1; j++) {
campo[i][j].setText(""+A[i][j]);
}
}
});
Button limpiarb = new Button("Limpiar");
limpiarb.setOnAction((ActionEvent t) -> {
for(int i=0; i<tamano+1; i++) {
for(int j=0; j<tamano+1; j++) {
campo[i][j].setText("0");
}
}
});
GridPane mainPane = new GridPane();
mainPane.setMinSize(650,350);
mainPane.setPadding(new Insets(10,10,10,10));
mainPane.setVgap(5);
mainPane.setHgap(5);
mainPane.setAlignment(Pos.CENTER);
mainPane.add(tamanoML, 0, 0);
mainPane.add(tamanoMS, 1, 0);
mainPane.add(resolverB,0,1);
mainPane.add(limpiarb,1,1);
for(int i=0; i<tamano+1; i++) {
r=i+1;
if(r<tamano+1) {
r=i+1;
campoL[i]=new Label("X"+r);
mainPane.add(campoL[i],i,2);
}else {
campoL[i]=new Label("R");
mainPane.add(campoL[i],i,2);
}
}
for(int i=0; i<tamano; i++) {
for(int j=0; j<tamano+1; j++) {
campo[i][j] = new TextField("0");
mainPane.add(campo[i][j],j,i+3);
}
}
tamanoMS.valueProperty().addListener((newValue) -> {
int s;
for(int i=0; i<tamano+1; i++) {
s=i+1;
if(s<tamano+1) {
s=i+1;
campoL[i]=new Label("X"+s);
mainPane.add(campoL[i],i,2);
}else {
campoL[i]=new Label("R");
mainPane.add(campoL[i],i,2);
}
}
for(int i=0; i<tamano; i++) {
for(int j=0; j<tamano+1; j++) {
campo[i][j] = new TextField("0");
mainPane.add(campo[i][j],j,i+3);
}
}
s=0;
});
Scene scene = new Scene(mainPane);
primaryStage.setScene(scene);
primaryStage.setTitle("Ventas del Dia");
primaryStage.show();
}
Ok so the first thing you want to do is rewrite your listener like this
tamanoMS.valueProperty().addListener((obs, oldValue, newValue) -> {
System.out.println("heard");
int s;
for(int i=0; i<newValue+1; i++) {
s=i+1;
if(s<newValue+1) {
s=i+1;
campoL[i]=new Label("X"+s);
mainPane.add(campoL[i],i,2);
}else {
campoL[i]=new Label("R");
mainPane.add(campoL[i],i,2);
}
}
for(int i=0; i<newValue; i++) {
for(int j=0; j<newValue+1; j++) {
campo[i][j] = new TextField("0");
mainPane.add(campo[i][j],j,i+3);
}
}
s=0;
});
I'm gonna be honest I don't quite understand why you need oldValue and obs but you do. However, the reason your matrix wasn't expanding was because you weren't updating tamano to the most recent number.
You also need to change your spinner to this so that is know the value that is coming out is an integer.
Spinner<Integer> tamanoMS =new Spinner<Integer>(1,5,0,1);

Runtime error SIGSEGV on SPOJ

I'm trying to solve problem ARDA1 - The hunt for Gollum on SPOJ
Here's the link: http://www.spoj.com/problems/ARDA1/
And here's my code:
#include <algorithm>
#include <string>
using namespace std;
string map[2010];
string marshes[310];
char str[310];
int main()
{
int N1, N2, M1, M2 = 0;
freopen("INPUT.txt","rt",stdin);
scanf("%d%d", &N1, &N2);
for (int i = 0; i < N1; i++) {
scanf("%s", &str);
marshes[i] = str;
}
scanf("%d%d", &M1, &M2);
for (int i = 0; i < M1; i++) {
scanf("%s", &str);
map[i] = str;
}
bool isFound = false;
for (int i = 0; i <= M1 - N1; i++)
for (int j = 0; j <= M2 - N2; j++) {
if (map[i][j] == marshes[0][0]) {
bool isSame = true;
for (int t = 0; t < N1; t++) {
if (marshes[t] != map[i+t].substr(j, N2)) {
isSame = false;
break;
}
}
if (isSame) {
printf("(%d,%d)\n", i+1, j+1);
isFound = true;
}
}
}
if (!isFound)
printf("NO MATCH FOUND...");
return 0;
}
But I got "Runtime error (SIGSEGV)" when I submit my solution. I know that we get SIGSEGV when trying to access elements out of bound or when there's not enough memory.
I checked my code but couldn't find anything wrong and it worked on my computer. Anyone can tell me what could be wrong here?

MPI min function in reduce

I am trying to find the minimum number in my array of integers, however, it returns 0.
import mpi.*;
import java.util.Random;
class AddIntSR
{
public static void main(String[] params) throws Exception
{
MPI.Init(params);
int me = MPI.COMM_WORLD.Rank();
int size = MPI.COMM_WORLD.Size();
final int CHUNKSIZE = 1;
final int ROOT = 0;
Random rg = new Random();
int [] bigBuf = new int[CHUNKSIZE *size];
int [] smallBuf = new int[CHUNKSIZE];
int [] minBuf = new int[1];
int localTotal = 0;
if (me == ROOT)
{
for(int i = 0; i< bigBuf.length; i++)
bigBuf[i] = rg.nextInt(10);
for(int i = 0; i< bigBuf.length; i++)
System.out.println("bigBuf "+bigBuf[i]);
}
MPI.COMM_WORLD.Scatter(bigBuf,0,CHUNKSIZE,MPI.INT,smallBuf,0,CHUNKSIZE,MPI.INT,ROOT);
if(me!= ROOT)
{
System.out.println("smallBuf "+me+ ": "+smallBuf[0]);
for(int i = 0; i < smallBuf.length; i++)
localTotal += smallBuf[i];
}
MPI.COMM_WORLD.Reduce(new int[]{localTotal},0,bigBuf,0,1,MPI.INT,MPI.MAX,ROOT);
MPI.COMM_WORLD.Reduce(new int[]{localTotal},0,minBuf,0,1,MPI.INT,MPI.MIN,ROOT);
if(me == ROOT)
{
System.out.println(bigBuf[0]);
System.out.println(minBuf[0]);
}
}
}
I am not sure why it does not work. The maximum function seems to work fine.
Also, how would I be able to access the integer that is sent to processor 0 so it is included in the min/max comparison?
Thank you.
The MIN reduction always results in 0 since localTotal is always 0 in rank ROOT and this is indeed the minimum value.
After the MPI.COMM_WORLD.Scatter call, all process including ROOT will have a piece of data in their smallBuf. Therefore you should remove the following conditional, i.e.:
if(me!= ROOT)
{
System.out.println("smallBuf "+me+ ": "+smallBuf[0]);
for(int i = 0; i < smallBuf.length; i++)
localTotal += smallBuf[i];
}
should become simply:
System.out.println("smallBuf "+me+ ": "+smallBuf[0]);
for(int i = 0; i < smallBuf.length; i++)
localTotal += smallBuf[i];

Resources