Пример #1
0
  public Main() {
    try {
      BufferedReader in;
      in = new BufferedReader(new InputStreamReader(System.in)); // Used for CCC
      int numLights = Integer.parseInt(in.readLine());
      int[] states = new int[numLights];
      for (int i = 0; i < numLights; i++) {
        states[i] = Integer.parseInt(in.readLine());
      }
      ArrayDeque<Scenario> Q = new ArrayDeque<Scenario>();
      HashMap<String, Integer> dp = new HashMap<String, Integer>();

      int moves = 0;
      Q.addLast(new Scenario(states));
      while (!Q.isEmpty()) {
        int size = Q.size();
        for (int q = 0; q < size; q++) {
          Scenario temp = Q.removeFirst();
          if (isEmpty(temp.states)) {
            System.out.println(moves);
            return;
          } else {
            for (int i = 0; i < temp.states.length; i++) {
              if (temp.states[i] == 0) {
                int[] newArr = Arrays.copyOf(temp.states, temp.states.length);
                newArr[i] = 1;
                newArr = fixArray(newArr);
                String arr = "";
                for (int p = 0; p < newArr.length; p++) arr += newArr[p];
                if (dp.get(arr) == null) {
                  dp.put(arr, moves);
                  Q.addLast(new Scenario(newArr));
                } else {
                  int val = dp.get(arr);
                  if (val != 0 && moves < val) {
                    dp.put(arr, moves);
                    Q.addLast(new Scenario(newArr));
                  }
                }

                // outputArr(newArr);
              }
            }
          }
        }
        moves++;
      }

    } catch (IOException e) {
      System.out.println("IO: General");
    }
  }
Пример #2
0
  static void solve() {
    int r = in.nextInt();
    int c = in.nextInt();
    int sy = in.nextInt() - 1;
    int sx = in.nextInt() - 1;
    int gy = in.nextInt() - 1;
    int gx = in.nextInt() - 1;
    char[][] t = new char[r][c];
    for (int i = 0; i < r; i++) {
      t[i] = in.next().toCharArray();
    }

    ArrayDeque<int[]> que = new ArrayDeque<>();
    BitSet visited = new BitSet();

    que.add(new int[] {sy, sx, 0});
    visited.set(sy * c + sx);

    int[] dx = {0, 1, 0, -1};
    int[] dy = {1, 0, -1, 0};
    int[][] dist = new int[r][c];

    while (!que.isEmpty()) {
      int[] p = que.pollFirst();
      int cy = p[0];
      int cx = p[1];
      int d = p[2];
      dist[cy][cx] = d;

      for (int i = 0; i < 4; i++) {
        int ny = cy + dy[i];
        int nx = cx + dx[i];
        if (ny < 0 || nx < 0 || r <= ny || c <= nx) continue;
        if (visited.get(ny * c + nx) || t[ny][nx] == '#') continue;
        que.add(new int[] {ny, nx, d + 1});
        visited.set(ny * c + nx);
      }
    }

    out.println(dist[gy][gx]);
  }