public: int findK(vector<vector<int>> &a, int n, int m, int k) { // 1 2 3 4 5 // 6 7 8 9 10 //11 12 13 14 15 //16 17 18 19 20 //21 22 23 24 25 // k=4 // 1 2 3 // 4 5 6 // 7 8 9 // Your code goes here // if(k==1) return a[0][0]; int lrow=0; int lcol=0; int urow=n-1; int ucol=m-1; int count=0; int i=0,j=0; while(count!=k){ //iterating from left to right for(j=lcol;j<=ucol;j++){ // cout<<"i:"<<i<<"j:"<<j<<endl; count++; if(count==k) { goto x; } } ucol--; j--; //iterating from up to down for(i=lrow+1;i<=urow;i++){ // cout<<"i:"<<i<<"j:"<<j<<endl; count++; if(count==k) { goto x; } } urow--; i--; //iterating from right to left for(j=ucol;j>=lcol;j--){ // cout<<"i:"<<i<<"j:"<<j<<endl; count++; if(count==k) { goto x; } } lcol++; j++; //iterating from down to up for(i=urow;i>=lrow+1;i--){ // cout<<"i:"<<i<<"j:"<<j<<endl; count++; if(count==k) { // cout<<"lrow:"<<lrow<<" urow:"<<urow<<" lcol:"<<lcol<<" ucol:"<<ucol<<endl; goto x; } } lrow++; i++; } x: return a[i][j]; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter