LeetCode --- 贪心算法 --- 874. 模拟行走机器人

这个可以自己标记一组数据,开始我是标记的角度然后去判断,但是我看了下题目给出的更好,使用数组标记信息简单明了直接了当:

public int RobotSim(int[] commands, int[][] obstacles) {
            int[] dx = new int[] {0, 1, 0, -1};
            int[] dy = new int[] {1, 0, -1, 0};
            var di = 0;
            var cIndex = 0;
            var x = 0;
            var y = 0;
            var hasSet = new HashSet<( int, int )>();
            var ans = 0;
            for (int i = 0; i < obstacles.GetLength(0); i++)
            {
                hasSet.Add((obstacles[i][0], obstacles[i][1]));
            }

            while (cIndex < commands.Length)
            {
                if (commands[cIndex] == -2)
                {
                    di = (di + 3) % 4;
                }
                else if (commands[cIndex] == -1)
                {
                    di = (di + 1) % 4;
                }
                else
                {
                    for (int i = 0; i < commands[cIndex]; i++)
                    {
                        int nx = x + dx[di];
                        int ny = y + dy[di];
                        if (!hasSet.Contains((nx, ny)))
                        {
                            x = nx;
                            y = ny;
                            ans = Math.Max(ans, x * x + y * y);
                        }
                        else
                            break;
                    }
                }

                cIndex++;
            }

            return ans;
    }
发布了71 篇原创文章 · 获赞 89 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/u012371712/article/details/104337237