My solution in Java, long and not mathematical but easy understanding


  • 0
    D
    public class Solution {
        public int[][] generateMatrix(int n) {
            int[][] result = new int[n][n];
            Robot eva = new Robot();// eva gogo~
            for (int i = 0; i < n*n; i++)
            {
                eva.go(result);
            }
            return result;
        }
    }
    
    class Robot
    {
        int val;
        int speedState;
        int x;
        int y;
        List<Speed> speedList;
        public Robot()
        {
            initSpeedList();
            val = 1;
            x = 0;
            y = 0;
            speedState = 0;
        }
        
        public void go(int[][] map)
        {
            map[x][y] = val;
            val++;
            edge(map);
            x += getCurrentSpeed().x;
            y += getCurrentSpeed().y;
        }
        
        private void initSpeedList()
        {
            speedList = new ArrayList();
            speedList.add(new Speed(0,1));
            speedList.add(new Speed(1,0));
            speedList.add(new Speed(0,-1));
            speedList.add(new Speed(-1,0));
        }
        
        private void edge(int[][] map)
        {
            int nextx = x + getCurrentSpeed().x;
            int nexty = y + getCurrentSpeed().y;
            if (nextx == map.length || nexty == map[0].length || nextx < 0 || nexty < 0)
            {
                turn();
                return;
            }
            if (map[nextx][nexty] != 0)
            {
                turn();
            }
        }
        
        private void turn()
        {
            speedState++;
            speedState = speedState%speedList.size();
        }
        
        private Speed getCurrentSpeed()
        {
            return speedList.get(speedState);
        }
    }
    
    class Speed
    {
        int x;
        int y;
        public Speed(int sx, int sy)
        {
            x = sx;
            y = sy;
        }
    }
    

    Just a robot, can put the number in, can turn right, turn right and turn right.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.