Public · Protected · Private
Spiral traversal of a 2 dimensional square array
Type: Public  |  Created: 2008-07-22  |  Frozen: Yes
« Previous Public Blog Next Public Blog »
Comments
  • You are given a 2 dimensional square array of odd lenth(1*1 or 3*3 or 5*5 etc) Do a spiral traversal of this array starting from center(clockwise or anticlockwise)
    2008-07-22 17:17
  • //Create an array and display it label1.Text = ""; int counter = 20; TwoDimArray = Array.CreateInstance(typeof(Int32), 5, 5); for (int i = 0; i < TwoDimArray.GetLength(0); i++) { for (int j = 0; j < TwoDimArray.GetLength(1); j++) { TwoDimArray.SetValue(counter, i, j); counter++; } } for (int i = 0; i < TwoDimArray.GetLength(0); i++) { for (int j = 0; j < TwoDimArray.GetLength(1); j++) { label1.Text += TwoDimArray.GetValue(i, j).ToString()+" "; } label1.Text += "\n\r"; } Traveavelit();
    2008-07-24 00:50
  • //Have three global variables stepx,stepy together define how mich to move. int stepx; int stepy; int centerX; private void Traveavelit() { int width = TwoDimArray.GetLength(0); int height = TwoDimArray.GetLength(1); label2.Text = ""; centerX = width / 2; ContinueTravel( centerX, centerX ); } private void ContinueTravel( int gx, int gy ) { int x = gx - centerX; int y = gy - centerX; if ((x == y) && (x < 1)) {//right stepx = 1; stepy = 0; } else if (((x + y) == 1) && (x > y)) {//up stepx = 0; stepy = 1; } else if (((x + y) == 0) && (y > x)) {//down stepx = 0; stepy = -1; } else if ((x == y) && (x > 0)) {//left stepx = -1; stepy = 0; } label2.Text += TwoDimArray.GetValue(gy, gx).ToString() + "\r\n"; if ((x == centerX) && (y + centerX == 0)) return; ContinueTravel( gx + stepx, gy + stepy ); }
    2008-07-24 00:52
  • I imagined a graph page. x=0,y=0 as center (also center of square) steps can be (1,0) - right (0,1) = up (0,-1) = down (-1,0) = left One more thing is whenever coordinate is 1,1 / 2,2 /3,3 .... we take a turn -- do you see a pattern? There is a pattern for all turns (identify them) and take turns (turn is basically changing stepx,stepy)
    2008-07-24 00:58
This blog is frozen. No new comments or edits allowed.