左螺旋陣(模擬法)

描述

一個n*m的左螺旋陣是一個從右上角開始逆時針方向旋轉,從n*m開始依次填寫數字直到1爲止的矩陣(類似於蚊香盤)。例如一個4*4的左螺旋矩陣是下面這個樣子的:

13 14 15 16

12 3 4 5

11 2 1 6

10 9 8 7

再比如一個5行4列的左螺旋陣是下面這個樣子的:

17 18 19 20

16 5 6 7

15 4 1 8

14 3 2 9

13 12 11 10

格式

輸入格式

一行,輸入兩個正整數n和m(2≤n,m≤30),分別表示行和列數

輸出格式

輸出對應的左螺旋矩陣

樣例

輸入樣例

6  4

輸出樣例

  21  22  23  24
  20   7   8   9
  19   6   1  10
  18   5   2  11
  17   4   3  12
  16  15  14  13

限制

時間限制:100 ms

內存限制:16384 KB

我的思路是:用while(1)外循環,設cnt_num初始值爲n*m,cnt_x=0,cnt_y=m-1,數組ans[][]全爲0,然後按順序從四個方向(左、下、右、上)while內循環走,他們分別都有自己的跳出的條件,舉個例子,跳出左的條件爲ans[cnt_x][cnt_y] == 0 && cnt_y >= 0。這樣一直到cnt_num==0跳出所有循環。

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

md,因爲提交前忘改一個值,這道題虧了70分。。。下面的代碼已經更新,應該沒問題了。

#include <iostream>
#include <string.h>
using namespace std;
int ans[35][35];

int main(){
	int m, n;
	scanf ("%d %d", &n, &m);	
	memset(ans, 0, sizeof(ans));
	int cnt_x = 0;
	int cnt_y = m-1;
	int cnt_num = n*m;
	while (1) {
		while (ans[cnt_x][cnt_y] == 0 && cnt_y >= 0) {	//左 
			ans[cnt_x][cnt_y] = cnt_num;
			cnt_num--;
			if(cnt_num == 0) {
				break;
			}
			cnt_y--;
		}
		cnt_y++;
		cnt_x++;
		while (ans[cnt_x][cnt_y] == 0 && cnt_x < n) {	//下 
			ans[cnt_x][cnt_y] = cnt_num;
			cnt_num--;
			if(cnt_num == 0) {
				break;
			}
			cnt_x++;
		}
		cnt_x--;
		cnt_y++;
		while (ans[cnt_x][cnt_y] == 0 && cnt_y < m) {	//右 
			ans[cnt_x][cnt_y] = cnt_num;
			cnt_num--;
			if(cnt_num == 0) {
				break;
			}			
			cnt_y++;
		}
		cnt_y--;
		cnt_x--;
		while (ans[cnt_x][cnt_y] == 0 && cnt_x >= 0) {	//上 
			ans[cnt_x][cnt_y] = cnt_num;
			cnt_num--;
			if(cnt_num == 0) {
				break;
			}			
			cnt_x--;			
		}
		cnt_x++;
		cnt_y--;
		if(cnt_num == 0) {
			break;
		}
	}
	for (int i=0; i<n; i++) {
		printf ("%4d", ans[i][0]);
		for (int j=1; j<m; j++) {
			printf ("%4d", ans[i][j]);
		}
		printf ("\n");
	}		
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章