0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

2次元配列の斜め方向のループ

Last updated at Posted at 2022-06-19

2次元配列の各要素にアクセスするとき、斜めの方向にアクセスする必要がある場合がありますが、よく忘れるのでメモしておきました。
以下、斜めに各要素を番号付けした配列を出力するコードです。

droop.cpp
#include<bits/stdc++.h>
using namespace std;

int main(){
    int n;
    cin >> n;
    vector<vector<int>> ans(n,vector<int>(n));
    int x=0; //通し番号
    //前半部分
    for( int k=0; k<n; ++k ){
        for( int i=k; i>=0; --i ){
            int j = k-i;
            ans[i][j] = x;
            ++x;
        }
    }
    //後半部分
    for( int k=n-2;k>=0; --k ){
        for( int i=k; i>=0; --i ){
            int j = k-i;
            ans[n-1-j][n-1-i] = x;
            ++x;
        }
    }
    //出力
    for( int i=0; i<n; ++i ){    
        for( int j=0; j<n; ++j ){
            if(ans[i][j]>9) cout << ans[i][j] << " ";
            else cout << ans[i][j] << "  ";
        }
        cout << endl;
    }
    return 0;
}

前半を数えた後、それをひっくり返したループで後半を数えました。$k$は斜めに見たときの列の要素数-1になっています。
($k+1=1,2,\cdots,n-1,n,n-1,n-2,\cdots,1$と変化します。ちなみに奇数番目の$k$は対角成分を含む列、偶数番目は対角成分を含まない列です。)

例えば、$n=5$で出力すると

0  2  5  9  14 
1  4  8  13 18 
3  7  12 17 21 
6  11 16 20 23 
10 15 19 22 24

$n=6$で出力すると

0  2  5  9  14 20 
1  4  8  13 19 25 
3  7  12 18 24 29 
6  11 17 23 28 32 
10 16 22 27 31 34 
15 21 26 30 33 35 

となります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?