生成1-N*N的矩陣,一圈一圈的

#include <iostream>
using namespace std;

int N;
int data[100][100];
bool visit[100][100];

void getNext(int status, int& nx, int &ny)
{
	switch (status)
	{
	case 0:
		//right
		nx = 0, ny = 1; break;
	case 1:
		//down
		nx = 1, ny = 0; break;
	case 2:
		//left
		nx = 0, ny = -1; break;
	case 3:
		//up
		nx = -1, ny = 0; break;
	}
}

bool isVaild(int x, int y)
{
	if(visit[x][y])
		return false;
	if( x < 0 || x > N -1 || y < 0 || y > N - 1)
		return false;
	return true;
}

int main()
{
	cin >> N;
	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < N; j++)
		{
			data[i][j] = 0;
			visit[i][j] = false;
		}
	}

	int status = 0;
	int cx = 0, cy =-1;
	int nx,ny;
	for(int num = 1; num <= N * N; )
	{
		getNext(status, nx, ny);
		cx += nx;
		cy += ny;
		if (isVaild(cx, cy))
		{
			data[cx][cy] = num;
			visit[cx][cy] = true;
			num++;
		}
		else
		{		
			status = (status + 1) % 4;
			cx -= nx;
			cy -= ny;
		}
	}

	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < N; j++)
		{
			cout << data[i][j] << " ";
		}
		cout << endl;
	}
	/*
	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < N; j++)
		{
			cout << visit[i][j] << " ";
		}
		cout << endl;
	}
	*/
}

發佈了136 篇原創文章 · 獲贊 164 · 訪問量 28萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章