Tuesday, October 20, 2015

Given a N*N square matrix, return an array of its anti-diagonals

http://qa.geeksforgeeks.org/4151/return-an-array-of-all-the-anti-diagonals

int n=A.size();
    int N=n-1;
    vector<pair<int,int>> search;
    for(int i=0;i<n;i++)
    {
        search.push_back(make_pair(0,i));
    }
    for(int i=1;i<n;i++)
    {
        search.push_back(make_pair(i,n-1));
    }
    vector <vector <int> > v;
   
    for(int i=0;i<search.size();i++)
    {
        int x=search[i].first;
        int y=search[i].second;
        vector<int > v1;
        while(x<n&&y>=0)
        {
            v1.push_back(A[x][y]);
            x+=1;
            y-=1;
        }
        v.push_back(v1);
    }
    return v;

No comments:

Post a Comment

Contributors

Translate