01/10/2018, 14:47

In ma trận m x n dạng xoắn ốc

Xin chào mọi người ạ, em có làm bài này mà không biết sai ở đâu, xin mọi ng giúp em với ạ. Đề là nhập vào m, n là số dòng và số cột của ma trạn, in ra các số từ 1 đến m*n theo đuơng xoắn ốc. Em bị sai khi nhập (6,3) và (7,9).

#include<iostream>

using namespace std;

int main() {
	int m, n;
	cin >> m >> n;
	int a[m][n];
	int dong = m, cot = n, k = 1, p = 0, i, j;
	while(k <= m*n){
		for(i = p; i < cot; i++) /*Loop to access the first row of the array*/
			a[p][i] = k++;
		for(i = p+1; i < dong; i++) /*Loop tp access the last column of the array*/
			a[i][cot-1] = k++;
		for(i = cot-2; i >=p; i--) /*Loop to access the last row of the array*/
			a[dong-1][i] = k++;
		for(i = dong-2; i > p; i--) /*Loop to access the first column of the array*/
			a[i][p] = k++;
		p++;dong --; cot --;
	}
	for(i = 0; i < m; i++){
		for(j = 0; j < n; j++)
			cout << a[i][j] << " ";
		cout << endl;
	}
}

du0n9 viết 17:00 ngày 01/10/2018

Vòng lặp của bạn có lỗi do 1 cột hoặc 1 dòng có thể được duyệt 2 lần
Mình sửa bằng cách thêm kiểm tra điều kiện

	while(k <= m*n){
		for(i = p; i < cot; i++) /*Loop to access the first row of the array*/
			a[p][i] = k++;
		for(i = p+1; i < dong; i++) /*Loop tp access the last column of the array*/
			a[i][cot-1] = k++;
		if ( p != dong-1){
			for(i = cot-2; i >=p; i--) /*Loop to access the last row of the array*/
				a[dong-1][i] = k++;
		}	
		if(p!=cot-1){
			for(i = dong-2; i > p; i--) /*Loop to access the first column of the array*/
				a[i][p] = k++;
		}	
		p++;dong --; cot --;
	}
Nobi Sewashi viết 16:52 ngày 01/10/2018

Em cảm ơn ạ <3 33333333

Bài liên quan
0