Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- /*
- given a connected undirectional unweighted graph
- you need to find the shortest distance between source node and destination node
- twist is you can only travel if they are having visitable as 1
- */
- /**
- important point to understand here -
- you can do a simple bfs , but you will visit the nodes only if they are visitable
- otherwise no
- */
- /*
- //inputs for visitable and graph
- 1 1 0 1 1
- 5 5
- 0 1
- 0 2
- 1 3
- 2 4
- 3 4
- 4
- expected output -
- The result is 3
- */
- @SuppressWarnings({"unused","unchecked"})
- public class A20250208a_atlassianOA {
- static Scanner sc = new Scanner(System.in);
- private static int[] getArray() {
- String[] sArr = sc.nextLine().split(" ");
- int[] arr = Arrays.stream(sArr).mapToInt(Integer::parseInt).toArray();
- return arr;
- }
- private static char[] getCharArray() {
- String[] sArr = sc.nextLine().split(" ");
- char[] cArr = new char[sArr.length];
- for (int i = 0; i < sArr.length; i++) {
- cArr[i] = sArr[i].charAt(0); // Take the first character of each string
- }
- return cArr;
- }
- private static int getMax(int[] arr) {
- int currMax = Integer.MIN_VALUE;
- for (int curr : arr) {
- currMax = Math.max(currMax, curr);
- }
- return currMax;
- }
- public static void main(String args[]) {
- // prepare the inputs
- int[] visitable = getArray();
- int[] tempArr = getArray();
- int nodes = tempArr[0];
- int edges = tempArr[1];
- ArrayList<Integer>[] adjList =(ArrayList<Integer>[]) new ArrayList[nodes];//explicit type conversion
- for(int i =0;i<nodes;i+=1){
- adjList[i] = new ArrayList<>();
- }
- int temp = edges;
- //fill up the graph
- while(temp!=0){
- temp-=1;
- tempArr = getArray();
- int n1 = tempArr[0];
- int n2 = tempArr[1];
- adjList[n1].add(n2);
- adjList[n2].add(n1);
- }
- Queue<Integer> q = new LinkedList<>();
- int[] level = new int[nodes];
- Arrays.fill(level,(int)1e8);//filling level with some big number
- int[] visited = new int[nodes];
- if(visitable[0]==1){
- visited[0] = 1;
- level[0] = 0;
- q.offer(0);//offer is safe than add
- }
- while(!q.isEmpty()){
- int parent = q.poll();
- for(int child:adjList[parent]){
- if(visitable[child]==1 && visited[child]==0){
- visited[child]=1;
- level[child] = level[parent]+1;
- q.offer(child);
- }
- }
- }
- tempArr = getArray();
- int res = level[tempArr[0]];
- System.out.println("The result is " + res);
- }
- }
- class Pair{
- int row;
- int col;
- public Pair(int i,int j){
- this.row = i;
- this.col = j;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement