模拟

Zigzag Matrix

Time Limit:1000MS Memory Limit:655360K
Total Submit:33 Accepted:17

Description

Produce a zig-zag array. A zig-zag array is a square arrangement of the first N*M integers, where the numbers increase sequentially as you zig-zag along the anti-diagonals of the array. The figure below shows the zigzag sequence.


For example, given (5, 5), (the number of row and columns), the zigzag matrix should be:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24

Input

There are multiple test cases, each test case contains one line with two integers N, M and a string D (1<=N*M<=10000).
N is the number of rows, M is the number of columns. D is the start direction, could be “Right” or “Down”. “Right” means the sequence should start from (0, 0) to (0, 1), and “Down” means the sequence should start from (0, 0) to (1, 0).

Output

For each test case, you should output the zigzag matrix.

Sample Input

2 2 Right
3 4 Down

Sample Output

0 1
2 3
0 2 3 8
1 4 7 9
5 6 10 11
//模拟
#include <iostream>
#include <cstdio>
using namespace std;
int N, M;
char D[10];
int map[10010];//题的关键转换为一维数组

void solve()
{
	int x, y;
	x = 0, y = 0;
	int dir;
	int ans = 0;
	map[x * M + y] = ans ++;
	while(!(x == N - 1 && y == M - 1))
	{
		if(y < M - 1)
		{
			dir = 1;
			y ++;
			map[x * M + y] = ans ++;
		}
		else if(x < N - 1)
		{
			dir = 3;
			x ++;
			map[x * M + y] = ans ++;
		}
		while(x != N -1 && y != 0)
		{
			dir = 2;
			x ++;
			y --;
			map[x * M + y] = ans ++;
		}
		if(y == 0)
		{
			if(x < N - 1)
			{
				dir = 3;
				x ++;
				map[x * M + y] = ans ++;
			}
			else if(y < M - 1)
			{
				dir = 1;
				y ++;
				map[x * M + y] = ans ++;
			}
		}
		else if(x == N - 1)
		{
			if(y < M - 1)
			{
				dir = 1;
				y ++;
				map[x * M + y] = ans ++;
			}
		}
		while(x != 0 && y != M - 1)
		{
			dir = 4;
			x --;
			y ++;
			map[x * M + y] = ans ++;
		}
	}
}

int main()
{
	while(scanf("%d%d%s", &N, &M, D) != EOF)
	{
		int i, j;
		if(D[0] == 'D')
		{
			int temp = N;
			N = M;
			M = temp;
		}
		solve();
		if(D[0] == 'R')
		{
			for(i = 0; i < N; ++ i)
			{
				for(j = 0; j < M; ++ j)
				{
					if(j) printf(" ");
					printf("%d", map[i * M + j]);
				}
				printf("\n");
			}
		}
		else if(D[0] == 'D')
		{
			for(i = 0; i < M; ++ i)
			{
				for(j = 0; j < N; ++ j)
				{
					if(j) printf(" ");
					printf("%d", map[j * M + i]);
				}
				printf("\n");
			}
		}
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值