diff --git a/GeeksForGeeks/April/22-4-24/GFG.java b/GeeksForGeeks/April/22-4-24/GFG.java new file mode 100644 index 0000000..dcd4d1e --- /dev/null +++ b/GeeksForGeeks/April/22-4-24/GFG.java @@ -0,0 +1,61 @@ +//{ Driver Code Starts +// Initial Template for Java + +import java.io.*; +import java.util.*; + +class GFG { + public static void main(String args[]) throws IOException { + BufferedReader read = + new BufferedReader(new InputStreamReader(System.in)); + int t = Integer.parseInt(read.readLine()); + while (t-- > 0) { + String s[] = read.readLine().split(" "); + int N = Integer.parseInt(s[0]); + int M = Integer.parseInt(s[1]); + int A[][] = new int[N][M]; + for (int i = 0; i < N; i++) { + String S[] = read.readLine().split(" "); + for (int j = 0; j < M; j++) { + A[i][j] = Integer.parseInt(S[j]); + } + } + Solution ob = new Solution(); + System.out.println(ob.minRow(N, M, A)); + } + } +} + +// } Driver Code Ends + + +// User function Template for Java + +class Solution +{ + int minRow(int n, int m, int a[][]) + { + // code here + int res=1; + int min = Integer.MAX_VALUE; + for(int i=0;i seen = new HashSet<>(Arrays.asList(deadends)); + if (seen.contains("0000")) + return -1; + if (target.equals("0000")) + return 0; + + int ans = 0; + Queue q = new ArrayDeque<>(Arrays.asList("0000")); + + while (!q.isEmpty()) + { + ++ans; + for (int sz = q.size(); sz > 0; --sz) + { + StringBuilder sb = new StringBuilder(q.poll()); + for (int i = 0; i < 4; ++i) + { + char cache = sb.charAt(i); + // Increase the i-th digit by 1. + sb.setCharAt(i, sb.charAt(i) == '9' ? '0' : (char) (sb.charAt(i) + 1)); + String word = sb.toString(); + + if (word.equals(target)) + return ans; + + if (!seen.contains(word)) + { + q.offer(word); + seen.add(word); + } + + sb.setCharAt(i, cache); + // Decrease the i-th digit by 1. + sb.setCharAt(i, sb.charAt(i) == '0' ? '9' : (char) (sb.charAt(i) - 1)); + word = sb.toString(); + + if (word.equals(target)) + return ans; + + if (!seen.contains(word)) + { + q.offer(word); + seen.add(word); + } + sb.setCharAt(i, cache); + } + } + } + + return -1; + } +}