[ create a new paste ] login | about

Link: http://codepad.org/ng3FvYcD    [ raw code | output | fork ]

C, pasted on Sep 23:
#include<stdio.h>
#include<stdlib.h>

int place2id(int, int, int);
void id2place(int,int,int *,int *);
void noqueen(int,int,int,int []);

int main(int argc, char **argv) {
  int n, a;
  int nq[400];
  int i, j, k;

  if (argc != 3) {
    fprintf(stderr, "%s: arg's num is 2 only.\n", argv[0]);
    return 1;
  }
  n = atoi(argv[1]);
  a = atoi(argv[2]);
  for (k = 0; k < 400; k++) nq[k]=0;
  id2place(n, a, &i, &j);
  noqueen(n,i,j,nq);
  for (k = 0; k < 400; k++) if (nq[k] == 1) printf(" %d",k);
  putchar('\n');
  return 0;
}

void noqueen(int n,int oi, int oj, int nq[]) {
  int **phase;
  if ((phase = malloc(sizeof(int *) * n)) != 0) {
    int k, r;
    for (k = 0; k < n; k++) phase[k] = 0;
    for (k = 0; k < n; k++) {
      if ((phase[k] = malloc(sizeof(int) * n)) == 0)
        break;
      else {
/*        if (k == 4) break; */
        for (r = 0; r < n; r++)
          phase[k][r] = 0;
      }
    }
    if (k == n) { /* when phase[][]'s allocasion is all success -- normal process is going */
      int x, y;
      int tx, ty;
      x = oj - 1;
      y = oi - 1;

      phase[y][x] = 1;
      for (tx = 0; tx < n; tx++)
        phase[y][tx] = 1;
      for (ty = 0; ty < n; ty++)
        phase[ty][x] = 1;
      tx = x; ty = y;
      while (tx >= 0 && ty >= 0) { tx--; ty--; }
      tx++; ty++;
      while (tx < n && ty < n) {
        phase[ty][tx] = 1;
        tx++; ty++;
      }
      while (tx < n && ty >= 0) { tx++; ty--; }
      tx--; ty++;
      while (tx >= 0 && ty < n) {
        phase[ty][tx] = 1;
        tx--; ty++;
      }
      for (ty = 0; ty < n; ty++)
        for (tx = 0; tx < n; tx++)
          if (phase[ty][tx])
            nq[place2id(n, ty + 1, tx + 1)] = 1;
    }
    for (k = 0; k < n; k++)
      free(phase[k]);
    free(phase);
  }
}

int place2id(int n, int i, int j) { return n * i - ( n - j); }

void id2place(int n, int a, int *i, int *j) {
  int k = a % n;
  if (k != 0){
    *i = a / n + 1;
    *j = a % n;
  } else {
    *i =a / n;
    *j = n;
  }
}
/* end */


Output:
1
/t: arg's num is 2 only.


Create a new paste based on this one


Comments: