【C / C++】螺旋填充一个矩阵:从左上角出发,顺时针行进,由外圈向内圈,用指定的序列螺旋填充矩阵。

#include <iostream>
#include <vector>

using namespace std;

using chr_t = char;
using coord_t = size_t;

struct coord {
    
     coord_t x, y; };

const chr_t content[] = {
    
     "ABCDEFGHIJKLMNOPQRSTUVWXYZ" };
const chr_t delim[] = " ";
const size_t CONTENT_SIZE = sizeof(content) / sizeof(chr_t) - 1;

inline bool next_pos(const size_t M, const size_t N, const vector<vector<chr_t>>& a, coord& c) {
    
    
	static unsigned direction = 0;
	for (unsigned i = 0; i < 4; ++i) {
    
    
		switch (direction) {
    
    
		case 0:
			if (c.y < N - 1 && a[c.x][c.y + 1] == 0) {
    
     ++c.y; return true; }
			else {
    
     direction = (direction + 1) % 4; }
			continue;
		case 1:
			if (c.x < M - 1 && a[c.x + 1][c.y] == 0) {
    
     ++c.x; return true; }
			else {
    
     direction = (direction + 1) % 4; }
			continue;
		case 2:
			if (c.y > 0 && a[c.x][c.y - 1] == 0) {
    
     --c.y; return true; }
			else {
    
     direction = (direction + 1) % 4; }
			continue;
		case 3:
			if (c.x > 0 && a[c.x - 1][c.y] == 0) {
    
     --c.x; return true; }
			else {
    
     direction = (direction + 1) % 4; }
			continue;
		}
	}
	return false;
}

int main() {
    
    
	size_t M, N;
	for (;;) {
    
    
		cout << "Input M, N:" << endl;
		cin >> M >> N;
		if (M == 0 && N == 0) return 0;
		vector<chr_t> t(N, 0);
		vector<vector<chr_t>> a(M, t);
		coord c = {
    
     0, 0 };
		coord_t& x = c.x, & y = c.y;
		size_t i = 0;
		do {
    
    
			a[x][y] = content[i];
			i = (i + 1) % CONTENT_SIZE;
		} while (next_pos(M, N, a, c) == true);
		cout << endl;
		for (vector<vector<chr_t>>::const_iterator i = a.cbegin(); i != a.cend(); ++i) {
    
    
			for (vector<chr_t>::const_iterator j = i->cbegin(); j != i->cend(); ++j) {
    
    
				cout << *j << delim;
			}
			cout << endl;
		}
		cout << endl;
	}
}

在这里插入图片描述

Guess you like

Origin blog.csdn.net/COFACTOR/article/details/118094427