Easy to understand Java BFS solution


  • 0
    S

    This is a shortest path problem that can be solved using standard BFS.

    class Solution {
        public int integerReplacement(int n) {
            HashSet<Long> visited = new HashSet<>();
            Queue<Long> queue = new LinkedList<>();
            queue.offer((long)n);
            visited.add((long)n);
            int level = 0;
            while(true) {
                Queue<Long> tmp = new LinkedList<>();
                while(!queue.isEmpty()) {
                    long i = queue.poll();
                    if(i == 1) {
                        return level;
                    }
                    if(i % 2 == 0) {
                        if(!visited.contains(i / 2)) {
                            tmp.offer(i / 2);
                            visited.add(i / 2);
                        }
                    }
                    else {
                        if(!visited.contains(i + 1)) {
                            tmp.offer(i + 1);
                            visited.add(i + 1);
                        }
                        if(!visited.contains(i - 1)) {
                            tmp.offer(i - 1);
                            visited.add(i - 1);
                        }
                    }
                }
                level++;
                queue = tmp;
            }
        }
    }
    

Log in to reply
 

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