基础训练 回形取数(模拟法)

拜拜、爱过 提交于 2020-02-28 21:13:47

Description
回形取数就是沿矩阵的边取数,若当前方向上无数可取或已经取过,则左转90度。一开始位于矩阵左上角,方向向下。
Input
输入第一行是两个不超过200的正整数m, n,表示矩阵的行和列。接下来m行每行n个整数,表示这个矩阵。
Output
输出只有一行,共mn个数,为输入矩阵回形取数得到的结果。数之间用一个空格分隔,行末不要有多余的空格。
Sample Input 1
3 3
1 2 3
4 5 6
7 8 9
Sample Output 1
1 4 7 8 9 6 3 2 5

别问,问就是模拟法

模拟法1
#include <iostream>
#include <string.h>
using namespace std;

int main() {
	int map[200][200];
	bool flag[200][200];
	memset(flag, true, sizeof(flag));
	int m, n;
	cin >> m >> n;
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			cin >> map[i][j];
		}
	}
	int i = 0, j = 0;
	int a = m * n;
	
	while (a) {
		while (i < m && flag[i][j]) {	//向下 
			cout << map[i][j];
		flag[i][j] = false;
		i++;
		a--;
		if (a != 0) 
			cout << ' ';
		else 
			cout << endl;
		}
		i--;	//此时i多加了一个,越界了,加回来 
		j++;	//j移动到下一个循环的开始
		 
		while (j < n && flag[i][j]) {	//向右 
			cout << map[i][j];
		flag[i][j] = false;
		j++;
		a--;
		if (a != 0) 
			cout << ' ';
		else 
			cout << endl;
		}
		j--;
		i--;
		
		while (i >= 0 && flag[i][j]) {	//向上 
			cout << map[i][j];
		flag[i][j] = false;
		i--;
		a--;
		if (a > 0) 
			cout << ' ';
		else 
			cout << endl;
		} 
		i++; 
		j--;  
		
		while (j >= 0 && flag[i][j]) {	//向左 
			cout << map[i][j];
		flag[i][j] = false;
		j--;
		a--;
		if (a != 0) 
			cout << ' ';
		else 
			cout << endl;
		}
		j++;
		i++;
	}	
	return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!