回形遍歷數組


描述

給定一個row行col列的整數數組array,要求從array[0][0]元素開始,按回形從外向內順時針順序遍歷整個數組。如圖所示:

輸入輸入的第一行上有兩個整數,依次為row和col。
余下有row行,每行包含col個整數,構成一個二維整數數組。
(注:輸入的row和col保證0 < row < 100, 0 < col < 100)輸出按遍歷順序輸出每個整數。每個整數占一行。樣例輸入

4 4
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

樣例輸出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include <memory.h>
#include <stdio.h>
using namespace std;

int a[105][105];
int main()
{
	int n,m;
    cin >> n >> m;
    for( int i = 1; i <= n ; i++ )
        for( int j = 1; j <= m; j++ )
        cin >> a[i][j];
        
    int row = 1, col = 1;
    while( row <= n || col <= m )
    {
        for( int i = row, j = col; j <= m && row <= n; j++ )
            cout << a[i][j] << endl;
        row++;
        for( int i = row, j = m; i <= n && col <= m; i++ )
            cout << a[i][j] << endl;
        m--;
        for( int i = n, j = m; j >= col && row <= n; j-- )
            cout << a[i][j] << endl;
        n--;
        for( int i = n, j = col; i >= row && col <= m; i-- )
            cout << a[i][j] << endl;
        col++;
    }
    return 0;
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM