Description

There is a robot, its task is to bury treasures in order on a N × M grids map, and each treasure can be represented by its weight, which is an integer.

The robot begins to bury the treasures from the top-left grid. Because it is stupid, it can only Go straight until the border or the next grid has already been buried a treasure, and then it turns right.

Its task is finished when all treasures are buried. Please output the treasure map as a N × M matrix.

Input

There are several test cases, each one contains two lines.

First line: two integers N and M (1 ≤ N, M ≤ 100), indicate the size of the map.

Second line: N × M integers, indicate the weight of the treasures in order.

Output

For each test case, output a N × M matrix contains the weight of the treasures buried by the robot. There is one space between two integers.

Sample Input

2 2
3 2 1 4
3 3
1 2 3 4 5 6 7 8 9

Sample Output

3 2
4 1
1 2 3
8 9 4
7 6 5

分析:

给出M和N,然后给出M*N个数,然后按照蛇形矩阵填数的方法,把数按顺序输出。

代码

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
int N,M;
int Map[102][102];
int a[10009];
int main()
{
    int up,down,left,right;     ///分别记录上边界,下边界,左边界,右边界
    while(~scanf("%d%d",&N,&M))
    {
        for(int i = 1; i <= N*M; i++)
            scanf("%d",&a[i]);
        up = 0;
        down = N+1;
        left = 0;
        right = M+1;
        int ccount = 1;
        while(1)
        {
            ///先向右填数
            if(up+1<down) ///必须要判断,上下边界相邻,不能填数了。同理左右边界相邻也不能填数了。
            {
                for(int i = left+1; i<right; i++)
                {
                    Map[up+1][i] = a[ccount++];
                }
                up++;
            }
            else break;
            ///然后往下走
            if(left<right-1)
            {
                for(int i = up+1; i < down; i++)
                {
                    Map[i][right-1] = a[ccount++];
                }
                right--;
            }
            else break;
            ///然后往左走
            if(up<down-1)
            {
                for(int i = right-1; i > left; i--)
                {
                    Map[down-1][i] = a[ccount++];
                }
                down--;
            }
            else break;
            ///然后往上走
            if(left+1<right)
            {
                for(int i = down-1; i > up; i--)
                {
                    Map[i][left+1] = a[ccount++];
                }
                left++;
            }
            else break;
        }
        for(int i = 1; i <= N; i++)
        {
            for(int j = 1; j <= M; j++)
            {
                if(j == 1) printf("%d",Map[i][j]);
                else printf(" %d",Map[i][j]);
            }
            printf("\n");
        }
    }
    return 0;
}
posted on 2017-06-04 17:59  渡……  阅读(206)  评论(0编辑  收藏  举报