Skip to content

Completed BFS-2-1#613

Open
pranavs0133 wants to merge 1 commit into
super30admin:mainfrom
pranavs0133:main
Open

Completed BFS-2-1#613
pranavs0133 wants to merge 1 commit into
super30admin:mainfrom
pranavs0133:main

Conversation

@pranavs0133
Copy link
Copy Markdown

No description provided.

@super30admin
Copy link
Copy Markdown
Owner

Your solution for the oranges rotting problem is correct and efficient in terms of worst-case time and space complexity. Well done on implementing the BFS approach correctly. However, there are a few points to improve:

  1. Early Termination: Inside the inner loop when you process a neighbor, you can check if freshOranges becomes zero and return time immediately (without waiting for the entire level to process and without having to do another minute). This would make your solution more efficient in practice. For example, in the reference solution, they check inside the inner loop and return as soon as fresh becomes zero.

  2. Space Complexity Comment: Your comment at the top says "SC - O(n)" but the space complexity of the BFS queue can be up to O(m*n) in the worst case. Please correct the comment to avoid confusion.

  3. Variable Naming: Your variable names are generally good, but consider using more descriptive names like row and col instead of r and c for better readability.

  4. Minute Counting: Your method of counting minutes by incrementing at the start of the while loop and then subtracting one at the end is correct, but it might be slightly unintuitive. Alternatively, you can initialize time to 0 and then after processing each level, increment time. Then you can break early when fresh becomes zero and return the current time. However, your current approach is acceptable.

Here is a slightly modified version that includes early termination:

public int orangesRotting(int[][] grid) {
    int freshOranges = 0;
    Queue<int[]> q = new LinkedList<>();
    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants