Kth element of Spiral Traversal

PHOTO EMBED

Sun Oct 10 2021 07:54:16 GMT+0000 (Coordinated Universal Time)

Saved by @zs #c++

	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];
        
    }
content_copyCOPY