+ 1
Iterate through a bidimensional array
I made an algorithm to iterate through a bidimensional array in a circular spiral, but it's not perfect for some cases. Can you help me fix it? for(i = 0; i < m/2; i++){ for(j = i; j < m - i; j++){ cout<<arr[i][j]<<" "; } for(j = i + 1; j < n - i; j++){ cout<<arr[j][m - i - 1]<<" "; } for(j = m - i - 2; j >= i; j--){ cout<<arr[n - i - 1][j]<<" "; } for(j = n -i - 2; j > i; j--){ cout<<arr[j][i]<<" "; } } m - the number of columns n - the number of rows IT DOES NOT WORK WHEN n IS ODD.
2 ответов
+ 4
@Kathy:
Adapted in Python, your third iteration with j has a wrong range, so I correct it ( i-1 instead i )...
def iter(a,m,n):
for i in range((m+1)//2):
for j in range(i, m - i):
a[i][j]=1
for j in range(i+1, n - i):
a[j][m - i - 1]=1
for j in range(m - i - 2, i-1, -1):
a[n - i - 1][j]=1
for j in range(n -i - 2, i, -1):
a[j][i]=1
I made testing with 0's array, filling with 1's and text display at each step... see complete script in code playground
https://code.sololearn.com/cZkLiwlXZ6iQ/#py
+ 2
You need to change "m/2" to "(m+1)/2" as shown below, because C++ rounds down when dividing integers and you need it to round up.
for(i = 0; i < (m+1)/2; i++){
for(j = i; j < m - i; j++){
cout<<arr[i][j]<<" ";
}
for(j = i + 1; j < n - i; j++){
cout<<arr[j][m - i - 1]<<" ";
}
for(j = m - i - 2; j > i; j--){
cout<<arr[n - i - 1][j]<<" ";
}
for(j = n -i - 2; j > i; j--){
cout<<arr[j][i]<<" ";
}
}