A simple CSharp solution, O(n^2)Time


  • 0
    Z
        public bool CanFinish(int numCourses, int[,] prerequisites) {
        
        for (int i = 0; i < prerequisites.Length; i += 2)
        {
            Stack<int> stack = new Stack<int>();
    
            stack.Push(prerequisites[i / 2, 0]);
            stack.Push(prerequisites[i / 2, 1]);
    
            for (int j = 0; j < prerequisites.Length; j += 2)
            {
                if (j == i)
                    continue;
    
                if (stack.Peek() == prerequisites[j / 2, 0])
                {
                    stack.Pop();
                    stack.Push(prerequisites[j / 2, 1]);
                }
            }
    
            int last = stack.Pop();
            int first = stack.Pop();
            if (last == first)
            {
                return false;
            }
        }
    
        return true;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.