Optimize counting N Queens algorithm