algorithm - How can I iterate through a two-dimensional array in a snail mode, with a single cycle? -
given two dimensional array, iterate through in snail mode , print out elements using one single cycle.
for example if given array is:
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
the program should print out:
10 15 20 25 30 31 32 33 34 29 24 19 14 13 12 11 16 21 26 27 28 23 18 17 22
so starting upper-left corner , arriving center of array.
here solution 1 loop:
it works when matrix is: n >= m
#include <iostream> using namespace std; int main() { // int arr[4][3] = {{0, 9, 8} , {1, 10 , 7} , {2, 11, 6} , {3, 4, 5}}; // int n = 4, m = 3; int arr[4][4] = {{0, 11, 10, 9} , {1, 12, 15, 8} , {2, 13, 14, 7} , {3, 4, 5, 6}}; int n = 4, m = 4; int row = 0, col = 0, turn = 0; bool istop = true; for(int nrelem = 0; nrelem <= (n*m); nrelem++) { //this part make left, bottom, right part ( u form ) if((row < n-1-turn) && (col != m-1) && (istop == true)) { cout << " " << arr[row][col]; row++; } else { if((row == n-1-turn) && (col < m-1-turn)) { cout << " " << arr[row][col]; col++; } else { if((col == m-1-turn) && (row > 0)) { cout << " " << arr[row][col]; row--; } else { istop = false; } } } // //and top backward parsing if((col > 0) && (istop == false)) { cout << " " << arr[row][col]; col--; } else { if (istop == false) { istop = true; turn++; row += turn; col += turn; } } } cout << endl; return 0; }
Comments
Post a Comment