[javascript]the answer is correct, but i got Time Limit Exceeded


  • 0
    K
    /**
     * @param {number} numCourses
     * @param {number[][]} prerequisites
     * @return {boolean}
     */
    var canFinish = function(numCourses, prerequisites) {
        var edgeGraph=[];
        //display(prerequisites)
        for(var i= 0; i<numCourses; i++) {
            edgeGraph[i]=[];
        } //新建二维数
        for(var x in prerequisites) {
                edgeGraph[prerequisites[x][0]][prerequisites[x][1]]=1;
        } //存入二维矩阵
        //display(edgeGraph);
        return TopologicalSort(edgeGraph,numCourses);
    };
    
    function TopologicalSort(edgeGraph,numCourses)
    {
        var counter=0;
        var preCounter=0;
        var visited=[];
        var noIn=1;
        for(var i=0; i<numCourses; i++)
            visited[i]=0; //遍历数组,0未访问,1已访问。
        while(counter!=numCourses) {
            for(var x in edgeGraph) {
                for(var x1 in edgeGraph[x]) {
                    if (edgeGraph[x][x1]==1) {
                        noIn=0;
                        break;
                    }
                    noIn=1;
                }//
                if (noIn && !visited[x]) {
                    visited[x]=1;
                    preCounter=counter; 
                    counter++;
                    for (var y in edgeGraph) {
                         if (edgeGraph[y][x]) {
                            edgeGraph[y][x]=0; //将出度设为0
                         }
                    }
                }//如果没有入度并且没有被访问
            }//遍历行
            if (preCounter==counter) {
                return false;
            }
        }
        return true;
    }

Log in to reply
 

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