ALDS_1_13_A 8 Queens

Calendar Clock iconCalendar Clock icon

AOJ

Table of contents

# Problem

http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_13_A

# Solution

// C++ 14
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <unordered_map>
#include <math.h>

#define ll long long
#define Int int
#define loop(x, start, end) for(Int x = start; x < end; x++)
#define loopdown(x, start, end) for(int x = start; x > end; x--)
#define rep(n) for(int x = 0; x < n; x++)
#define span(a,x,y) a.begin()+x,a.begin()+y
#define span_all(a) a.begin(),a.end()
#define len(x) (x.size())
#define last(x) (*(x.end()-1))

using namespace std;
#define MAX_K 
#define W 8
Int K;
bool B[W][W];

#define FREE -1
#define NOT_FREE 1

vector<Int> rows(W, FREE), cols(W, FREE), dpos(W*2-1, FREE), dneg(W*2-1, FREE);

void input() {
  Int r, c;
  cin >> K;

  loop(r,0,W) {
    loop(c,0,W) {
      B[r][c] = false;
    }
  }

  loop(k,0,K) {
    cin >> r >> c;
    B[r][c] = true;
  }
}

void dump() {
  // Filter the answer
  loop(c,0,W) {
    loop(r,0,W) {
      if (B[r][c]) {
        if (rows[c] != r) return;
      }
    }
  }

  loop(c,0,W) {
    loop(r,0,W) {
      if (rows[r] == c) cout << 'Q';
      else cout << '.';
    }
    cout << endl;
  }
}

bool is_free(Int col, Int row) {
  return cols[row] == FREE && dpos[col + row] == FREE && dneg[col - row + W - 1] == FREE;
}

void rec(Int col) {
  if (col == W) {
    dump(); return;
  }

  loop(row,0,W) {
    if (!is_free(col, row)) continue;
    rows[col] = row;
    cols[row] = dpos[col + row] = dneg[col - row + W - 1] = NOT_FREE;

    rec(col + 1);

    rows[col] = cols[row] = dpos[col + row] = dneg[col - row + W - 1] = FREE;
  }
}

void solve() {
  rec(0);
}

int main(void) {
  input();
  solve();
}

Remote freelancer. A web and mobile application enginner.
Traveling around the world based on East Asia.
I'm looking forward to your job offers from all over the world!

Offer jobs or contact me!

Comments