Exemple #1
0
pair <int , vector<edge> > PRIM (vector <vector<edge>> adjList) // O (E logV)
{
    int N = adjList.size() , cost = 0;
    vector<int> visited (N , 0) ;
    vector<int> visited2 (N , 0) ;
    vector<edge> Graph ;

    priority_queue <edge> queueEdges ; // 1) priority_queue to sort edges
    // queueEdges.push(edge(-1,0,0)); //add base edge
    for(int j = 0 ; j<adjList.size() ; ++j)
    {
        for(int i = j+1 ; i<adjList[j].size() ; ++i)    //3) Iterate on adjacent edges & add new edges, using e.to as src
        {
            edge conectedEdge = adjList[j][i];
            // cout<< conectedEdge.weight<<" ";
            queueEdges.push(conectedEdge);
        }
        // cout<<endl;
    }

    cout<<"queueEdgesSize: "<< queueEdges.size()<<endl;
    while(!queueEdges.empty())
    {

        edge newEdge = queueEdges.top();
        queueEdges.pop();

        if ( visited2[newEdge.from] > 1 || visited2[newEdge.to] > 1 ) continue ;
        visited2[newEdge.from] ++ ;
        visited2[newEdge.to] ++ ;

        cost+= newEdge.weight;
        Graph.push_back(newEdge);
        if(Graph.size()==N-1) break ;
    }

    return make_pair(cost, Graph );
}
Exemple #2
0
 bool isValidSudoku(vector<vector<char>>& board) {
     int rows=board.size();
     int cols=board[0].size();
     if(rows==0) {
         return true;
     }
     vector<bool> visited(10, false);
     // Traverse column by column
     for(int i=0;i<cols;i++) {
         for(int j=0;j<rows;j++) {
             if(board[j][i]!='.') {
                 if(visited[board[j][i]-'0']) {
                     return false;
                 }
                 else {
                     visited[board[j][i]-'0']=true;
                 }
             }
         }
         clear(visited);
     }
     // Traverse row by row
     for(int i=0;i<rows;i++) {
         for(int j=0;j<cols;j++) {
             if(board[i][j]!='.') {
                 if(visited[board[i][j]-'0']) {
                     return false;
                 }
                 else {
                     visited[board[i][j]-'0']=true;
                 }
             }
         }
         clear(visited);
     }
     vector<bool> visited2(10, false);
     vector<bool> visited3(10, false);
     vector<bool> *ref;
     for(int i=0;i<rows;) {
         for(int j=0;j<cols;j++) {
             if(j<3)
                 ref=&visited;
             else if(j<6)
                 ref=&visited2;
             else 
                 ref=&visited3;
             if(board[i][j]!='.') {
                 if((*ref)[board[i][j]-'0']) {
                     cout<<i<<'\t'<<j<<endl;
                     return false;
                 }
                 else {
                    (*ref)[board[i][j]-'0']=true; 
                 }
             }
         }
         i++;
         if(i%3==0) {
             clear(visited);
             clear(visited2);
             clear(visited3);
         }
     }
     return true;
 }