Zigzag Matrix(模拟)

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;
}


你可能感兴趣的:(Zigzag Matrix(模拟))