日期:2014-05-18 浏览次数:20755 次
Console.WriteLine("请输入一个整数"); int count = Convert.ToInt32(Console.ReadLine()); int[,] array = new int[count, count]; int size = int.Parse(Math.Sqrt(array.Length).ToString()); int row = 0, column = 0, n = 1, num = 1; bool bo = true; while (bo) { row = column = n - 1; while (column <= size - n) { if (array[row, column] != 0) if (array[row, ++column] != 0) { bo = false; break; } array[row, column] = num++; column++; } if (!bo) break; column--; while (row <= size - n) { if (array[row, column] != 0) if (array[++row, column] != 0 || row == size-1) { bo = false; break; } array[row, column] = num++; row++; } if (!bo) break; row--; while (row == column) { row--; column--; if (array[row, column] != 0) break; array[row, column] = num++; } n++; } for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { Console.Write(array[i, j].ToString() + " "); } Console.WriteLine(); } Console.Read();
------解决方案--------------------
int inputNumber = 6; //输入参数 int row = Convert.ToInt32(Math.Sqrt(inputNumber * 2 + 1 / 4) - 1 / 2); int[,] array = new int[row, row]; int columnIndex = -1; int rowIndex = 0; int mode=0; //0 行走, 1 斜走 , 2 列走 for (int i=1; i<=inputNumber ; i++ ) { switch (mode) { case 0: columnIndex++; if ( columnIndex <row && array[rowIndex, columnIndex] == 0) { array[rowIndex, columnIndex] = i; } else { i--; columnIndex--; mode = 1; } break; case 1: rowIndex++; columnIndex--; if (rowIndex <row && columnIndex >=0 && array[rowIndex, columnIndex] == 0 ) { array[rowIndex, columnIndex] =i; } else { i--; rowIndex--; columnIndex++; mode = 2; } break;