Sunday, August 29, 2021

LeetCode Medium: Course Schedule

 The next problem in the current coding spree was:

Problem Name: Course Schedule

Problem Descriptionhttps://leetcode.com/problems/course-schedule/

Problem Approach used: Detecting cycles on the directed graph pf dependencies using DFS to solve in O(V+E) where V is the number of courses in the input and E is the number of edges between them.

Time ComplexityO(lg n) worst-case time and O(1) auxiliary space complexity


Java Solution:


//Cycle detection

// package com.projects.cv.course_schedule;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Solution {

    // private static Logger logger = Logger.getLogger("MyLogger");
    int nodes;


    public boolean canFinish(int numCourses, int[][] prerequisites) {

        if (prerequisites == null)
            return false;
        int pL = prerequisites.length;
        nodes = numCourses;

        // Build directed graph
        Map<Integer, List<Integer>> g = new HashMap<>();
        for (int i=0; i<pL; i++) {
            if (!g.containsKey(prerequisites[i][0]))
                g.put(prerequisites[i][0], new ArrayList<>());
            g.get(prerequisites[i][0]).add(prerequisites[i][1]);
        }

        System.out.println(g);

        //Create visited to prevent re-visiting
        int visited[] = new int[numCourses];

        for (int i=0; i<numCourses; i++) {
            if (visited[i] == 0) {
                if (hasCycleDfs(g, visited, i, -1))
                    return false;
            }
        }

        return true;

    }

    private boolean hasCycleDfs( Map<Integer, List<Integer>> g, int[] visited, int n, int parent) {
        if (visited[n] == -1) {
            //current exploration path
            System.out.println("cycle found at u(" + parent + ")->v(" + n + ")");
            return true;
        }
        if (visited[n] == 1) {
            return false;
        }

        visited[n] = -1;

        if (g.get(n) == null) { // tackle bad callers
            visited[n] = 1;
            return false;
        }

        for (int neighBr : g.get(n)) {
            if (hasCycleDfs(g, visited, neighBr, n))
                return true;
        }

        visited[n] = 1;

        return false;
    }

    // public static void main(String[] args) {
    //     Solution s = new Solution();
    //     int[][] deps = {{1, 0}};
    //     s.canFinish(2, deps);
    // }

}



Love! ❤️ 
#Lets #Code

Follow us on :



https://twitter.com/ThinkAlgorithms

https://www.facebook.com/theAlgorithmicCoder

 




GeeksforGeeks Medium: Find the Number of Islands

Yesterday I solved a few hands-on coding problems using Java programming language.


I came across this easy problem(called Medium there) over GfG, to turn on the inertia:


Problem: Find the Number of Islands

Problem Descriptionhttps://practice.geeksforgeeks.org/problems/find-the-number-of-islands 

Problem Approach: DFS

Time Complexity: O(V) where v = number of cells in the input grid

One Java Solution:


// { Driver Code Starts
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine().trim());
        while(T-->0)
        {
            String[] s = br.readLine().trim().split(" ");
            int n = Integer.parseInt(s[0]);
            int m = Integer.parseInt(s[1]);
            char[][] grid = new char[n][m];
            for(int i = 0; i < n; i++){
                String[] S = br.readLine().trim().split(" ");
                for(int j = 0; j < m; j++){
                    grid[i][j] = S[j].charAt(0);
                }
            }
            Solution obj = new Solution();
            int ans = obj.numIslands(grid);
            System.out.println(ans);
        }
    }
}// } Driver Code Ends



class Solution
{
    int r, c;
    byte[] xOffset = {1, 1, 1, 0, -1, -1, -1, 0};
    byte[] yOffset = {1, 0, -1, -1, -1, 0, 1, 1};
    
    //Function to find the number of islands.
    public int numIslands(char[][] grid)
    {
        // Code here
        r = grid.length;
        c = grid[0].length;
        
        boolean[][] visited = new boolean[r][c];
        int cnt = 0;
        for (int i=0; i<r; i++) {
            for(int j=0; j<c; j++) {
                if (grid[i][j]=='1' && !visited[i][j]) {
                    dfs(grid, visited, i, j);
                    cnt++;
                }
            }
        }
        
        return cnt;
    }
    
    private void dfs (char[][] grid, boolean[][] visited, int x, int y) {
        //input validation
        if (!valid (grid, x, y) || visited[x][y]==true) {
            return;
        }
        
        visited[x][y] = true;
        
        for (int i=0; i<8; i++) {
            int newX = x + xOffset[i];
            int newY = y + yOffset[i];
            
            if(valid(grid, newX, newY) && !visited[newX][newY]) {
                dfs(grid, visited, newX, newY);
            }
        }
    }
    
    boolean valid (char[][]grid, int x, int y) {
        if (x<0 || x>=r || y<0 || y>=c || grid[x][y] == '0'){
            return false;
        }
        return true;
    }
}



Do share your thoughts and feel free to talk about the alternatives/optimisations you feel can be done in the comment section!


Love! ❤️ 
#Lets #Code

Follow us on :

https://twitter.com/ThinkAlgorithms
 https://www.facebook.com/theAlgorithmicCoder

 

 



Restarting Shorter and More Intense Problem-Solving Sprints

Hello Fellas,


After a long break, I have re-started #Problem #Solving #Tutorials using DS/Algorithms over (this) Let's Code Blog, but this time, it's gonna be consisting more intense but shorter #Coding #Sprints over weekends and somewhat lesser live-videos!! :D

Join me and get the weekend puzzle-solver activated in you!


✌️
#LetsCode

Featured Post

interviewBit Medium: Palindrome Partitioning II

Problem Name:  Palindrome Partitioning II Problem Description : https://www.interviewbit.com/problems/palindrome-partitioning-ii/ Problem Ap...