結果
問題 | No.3 ビットすごろく |
ユーザー |
|
提出日時 | 2020-05-24 18:24:29 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 173 ms / 5,000 ms |
コード長 | 2,604 bytes |
コンパイル時間 | 4,080 ms |
コンパイル使用メモリ | 77,960 KB |
実行使用メモリ | 56,788 KB |
最終ジャッジ日時 | 2024-07-01 09:49:36 |
合計ジャッジ時間 | 9,783 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 33 |
ソースコード
package yukicoder.level2.bitsugoroku; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class BitSugorokuRecursive { private Integer goal; public static void main(String[] args) { new BitSugorokuRecursive().execute(); } private void execute() { goal = read(); Integer firstLocation = 1; int minimumMovingNum = calcMinimanMovingNumber(firstLocation); output(minimumMovingNum); } private int calcMinimanMovingNumber(Integer firstLocation) { Set<Integer> presentLocations = new HashSet<>(); presentLocations.add(firstLocation); Set<Integer> pastLocations = new HashSet<>(); pastLocations.add(firstLocation); return goToNext(pastLocations, presentLocations, 1); } private int goToNext(Set<Integer> pastLocations, Set<Integer> presentLocations, int count) { if(presentLocations.isEmpty()) { return -1; } if(presentLocations.contains(goal)) { return count; } Set<Integer> newLocations = new HashSet<Integer>(); for (Integer presentLocation : presentLocations) { int movingDistance = calcMovingDistance(presentLocation); Integer nextForwardLocation = presentLocation + movingDistance; if(canMoveTo(nextForwardLocation, pastLocations)) { newLocations.add(nextForwardLocation); pastLocations.add(nextForwardLocation); } Integer nextBackwordLocation = presentLocation - movingDistance; if(canMoveTo(nextBackwordLocation, pastLocations)) { newLocations.add(nextBackwordLocation); pastLocations.add(nextBackwordLocation); } } return goToNext(pastLocations, newLocations, ++count); } private boolean canMoveTo(Integer location,Set<Integer> pastNumbers) { return 1 <= location && location <= goal && pastNumbers.contains(location) == false; } /** * Moving distance is defined as the number of "1"s of the "location" represented in binary. * This method calc the number of "1"s of the "location" represented in binary. * @param location * @return the number of "1"s. */ private int calcMovingDistance(Integer location) { return countOneNumberInBinaly(location, 0); } private Integer countOneNumberInBinaly(Integer decimal, int count) { if(decimal < 1) { return count; } int base = 2; int digit = 1; while(digit * base <= decimal) { digit *= base; } Integer newDecimal = decimal - digit; return countOneNumberInBinaly(newDecimal, ++count); } private void output(int size) { System.out.println(size); } private int read() { @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); return sc.nextInt(); } }