zoukankan      html  css  js  c++  java
  • Spiral Matrix——螺旋矩阵

            private static void PrintSpiral ()
            {
                int number = 3;
    
                int[,] spiralArr = Spiral(number);
    
                for (int i = 0; i < number; i++)
                {
                    for (int j = 0; j < number; j++)
                    {
                        Console.Write(spiralArr[i, j] + " ");
                    }
                    Console.Write("\n");
                }
            }
    
            static int[,] Spiral ( int number )
            {
                var position = new { x = -1, y = 0 };
                var directions = new[] { 
                    new { x = 1, y = 0 },
                    new { x = 0, y = 1 },
                    new { x = -1, y = 0 },
                    new { x = 0, y = -1 }
                };
    
                var sequence = (
                    from n in Enumerable.Range(1, number)
                    from o in Enumerable.Repeat(n, n != number ? 2 : 1)
                    select o
                ).Reverse().ToList();
    
                var result = new int[number, number];
    
                int currentValue = 1;
    
                for (int i = 0; i < sequence.Count; i++)
                {
                    var direction = directions[i % directions.Length];
    
                    for (int j = 0; j < sequence[i]; j++)
                    {
                        position = new
                        {
                            x = position.x + direction.x,
                            y = position.y + direction.y
                        };
    
                        result[position.y, position.x] = currentValue;
                        currentValue++;
                    }
                }
    
                return result;
            }
    

      

  • 相关阅读:
    frog-jump
    nth-digit
    binary-watch
    elimination-game
    evaluate-division
    random-pick-index
    integer-replacement
    rotate-function
    longest-substring-with-at-least-k-repeating-characters
    decode-string
  • 原文地址:https://www.cnblogs.com/scottgu/p/2424055.html
Copyright © 2011-2022 走看看