2d Array in Spiral Order

后端 未结 6 871
失恋的感觉
失恋的感觉 2020-12-20 00:30

I\'m trying to fill an array in spiral order. So far, I can print the array in spiral order, but is there a way to modify the array so that i can fill it in spiral order and

6条回答
  •  北海茫月
    2020-12-20 00:50

    Not the most efficient, but it should work: g is the array. I'm also using exceptions to control logic.

    public static void spiralFill()
    {
        x = (g.length-1)/2;
        y = (g[0].length-1)/2;
    
        try
        {
            while(true)
            {
                 east();
                 south();
                 step++;
                 west();
                 north();
                 step++;        
            }
        }
        catch(ArrayIndexOutOfBoundsException e)
        {
    
        }
    }
    
    public static void east()
    {
    for(int i = 0; i < step; i++)
    {
            g[x][y] = count;
            count++;
        x++;
        }
    }
    public static void south()
    {
        for(int i = 0; i < step; i++)
        {
            g[x][y] = count;
            count++;
            y--;
        }
    }   
    public static void west()
    {
        for(int i = 0; i < step; i++)
        {
             g[x][y] = count;
             count++;
             x--;
        }
    }   
    public static void north()
    {
       for(int i = 0; i < step; i++)
       {
           g[x][y] = count;
           count++;
           y++;
       }
    }   
    

提交回复
热议问题