Print matrix in spiral order

Input:

3

Output:

1 2 3
8 9 4
7 6 5

Code C++:

void spiral_matrix(const int n) {
    vector<vector<int>> a;
    a.assign(n+1, vector<int>(n+1,0));
    
    int cnt = 0;
    int i = 1, j = 1;
    
    while(cnt < n*n) {
        // left to right
        while(j <= n && a[i][j] == 0) {
            a[i][j] = ++cnt;
            j++;
        }
        j--; i++;
        
        // top to bot
        while(i <= n && a[i][j] == 0) {
            a[i][j] = ++cnt;
            i++;
        }
        i--; j--;
        
        // right to left
        while(j >= 1 && a[i][j] == 0) {
            a[i][j] = ++cnt;
            j--;
        }
        j++; i--;
        
        // bot to top
        while(i >= 1 && a[i][j] == 0) {
            a[i][j] = ++cnt;
            i--;
        }
        i++; j++;
    }
    
    
    
    // print result
    for(int i = 1; i < (int)a.size(); i++) {
        for(int j = 1; j < (int)a[1].size(); j++)
            cout << a[i][j] << ' ';
        cout << '\n';
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s