Given N and M find all stepping numbers in range N to M
The stepping number:
A number is called as a stepping number if the adjacent digits have a difference of 1.
e.g 123 is stepping number, but 358 is not a stepping number
Example:
N = 10, M = 20
all stepping numbers are 10 , 12
Return the numbers in sorted order.
Solution:
BFS
public class Solution { static class Node { int val;
public Node(int val) { this.val = val; }
public boolean isValid(int n, int m) { return val >= n && val <= m; }
public int lastDigit() { return val % 10; }
public int addDigit(int d) { return val * 10 + d; }
public boolean possible(int m) { return val <= m; }
@Override public int hashCode() { return val; }
@Override public boolean equals(Object o) { Node n = (Node) o; return n.val == val; } }
public ArrayList<Integer> stepnum(int A, int B) { ArrayList<Integer> result = new ArrayList<>(); Queue<Node> queue = new ArrayDeque<>(); Set<Node> visited = new HashSet<>(); for (int i = 0; i <= 9; i ++) { Node node = new Node(i); queue.offer(node); visited.add(node); } while (!queue.isEmpty()) { Node curr = queue.poll(); if (curr.isValid(A, B)) { result.add(curr.val); } int lastDigit = curr.lastDigit(); if (lastDigit >= 1) { Node next = new Node(curr.addDigit(lastDigit - 1)); if (next.possible(B) && visited.add(next)) { queue.offer(next); } } if (lastDigit < 9) { Node next = new Node(curr.addDigit(lastDigit + 1)); if (next.possible(B) && visited.add(next)) { queue.offer(next); } } } Collections.sort(result); return result; } }