Fighting Ant

Ant can be great while elephant can be chickenshit

导航

回顾一个面试题

Posted on 2008-07-11 15:37  Nillson  阅读(384)  评论(0编辑  收藏  举报

关于算法面试了两个题目:第一个是判断两个平面内的矩形是否可能发生碰撞;第二个是要写出逐层遍历二叉树的算法。个人感觉都不是很难,下面给出我的思路和解法。

设计一个数据结构来表示矩形,并用该结构作为参数来实现判断两个巨型是否发生碰撞的函数。

struct Rectangle
    {
        public Point leftUp;
        public Point rightDown;
    }
    class HitCheck
    {
        private Rectangle rectA = new Rectangle();
        private Rectangle rectB = new Rectangle();
        public HitCheck(Rectangle recA, Rectangle recB)
        {
            rectA = recA;
            rectB = recB;
        }
        public bool IsHited()
        {
            if (rectA.leftUp.X > rectB.rightDown.X || rectA.rightDown.X < rectB.leftUp.X || rectA.leftUp.Y > rectB.rightDown.Y || rectA.rightDown.Y < rectB.leftUp.Y)//如果左矩形的右边框在右矩形左边,左边框在右矩形右边,上边框在右矩形下边,下边框在右矩形上边则不相交,反之相交。
            {
                return false;
            }
            else if (rectB.leftUp.X > rectA.rightDown.X || rectB.rightDown.X < rectA.leftUp.X || rectB.leftUp.Y > rectA.rightDown.Y || rectB.rightDown.Y < rectA.leftUp.Y)
            {
                return false;
            }
            return true;
        }
    }

设计一个算法来“逐层”遍历二叉树。