Since a queen per row and a queen per column are both required, every candidate is a rearrangement of 0 to n - 1, held in an int[] where index r stores the queen's column in that row. The JDK offers no permutation generator, so the code includes nextPermutation, the classic swap-and-reverse step that advances the array to its lexicographic successor and reports false when none exists. Filling the array with 0, 1, …, n - 1 already gives the smallest ordering, which is why the loop is a do/while: the body tests that first arrangement before the condition advances it. Each arrangement then needs one diagonal test per pair of rows, Math.abs(cols[r1] - cols[r2]) == r2 - r1, and a keeper is stored as cols.clone() because the array is rewritten in place.