Algorithm - count the number of all subviews on a view

Keywords: iOS

Since then, I have no intention to love good night
Let him go down to the West Tower in the bright moon

Preface

Count the number of subviews on a view. Subviews containing subviews

Realization way

recursion

DFS depth first traversal

queue

BFS breadth first traversal

code implementation

recursion

Thoughts:

Return 0 when the view is empty
 Return 1 when the view has no subviews
 When a view has subviews:
    The current number is count=1
    Traverses all subviews of the current view, and recurses the subviews separately
    NSInteger calculateAllSubviewsWithDFS(UIView *view) {
        if (view == nil) { // Return 0 when the view is empty
            return 0;
        } else if (view.subviews.count == 0) { // Return 1 when the view has no subviews
            return 1;
        } else {
            NSInteger count = 1;
            for (NSInteger i = 0; i < view.subviews.count; i++) {
                count += calculateAllSubviewsWithDFS(view.subviews[i]);
            }
            return count;
        }
    }

queue

Thoughts:

Return 0 when the view is empty
 Return 1 when the view has no subviews
 When a view has subviews:
    The current number is count=1
    Create queue
    Queue entry
    When the queue is not empty
    Take out the first view in the queue and save it
    Calculate the number of subviews of the first view
    The first view is removed from the queue after calculation
    Traverse all subviews of the first view and queue
    
    NSInteger calculateAllSubviewsWithBFS(UIView *view) {
        if (view == nil) { // Return 0 when the view is empty
            return 0;
        } else if (view.subviews.count == 0) { // Return 1 when the view has no subviews
            return 1;
        } else { // When a view has subviews
            NSInteger count = 1;
            //Create queue
            NSMutableArray *arrayM = [NSMutableArray array];
            //Queue entry
            [arrayM addObject:view];
            // When the queue is not empty
            while (arrayM.count) {
                // Take out the first view of the queue
                UIView *subview = arrayM[0];
                //Delete first view of queue
                [arrayM removeObject:subview];
                //Calculate the number of subviews of the first view
                count += subview.subviews.count;
                // Traverse all subviews of the first view and queue
                for (NSInteger i = 0; i < subview.subviews.count; i++) {
                    // Queue entry
                    [arrayM addObject:subview.subviews[i]];
                }
            }
            return count;
        }
    }

Posted by phpusers on Thu, 17 Oct 2019 10:00:29 -0700