User Tools

Site Tools


the_eight_queens_solver

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
the_eight_queens_solver [2012/02/21 07:24] xjiathe_eight_queens_solver [2012/02/23 14:02] (current) xjia
Line 1: Line 1:
-<code>+<code java>
 /* The eight queens solver */ /* The eight queens solver */
  
-int main(string[] args) {+int main(string[ ] args) {
   int N;   int N;
-  int[] row, col, diag1, diag2;+  int[] row, col
 +  int[][] d;
      
   N = 8;   N = 8;
   row = new int[N];   row = new int[N];
   col = new int[N];   col = new int[N];
-  diag1 = new int[N+N-1]; +  d = new int[][2]; 
-  diag2 = new int[N+N-1];+  d[0] = new int[N+N-1]; 
 +  d[1] = new int[N+N-1];
      
-  fill(row, 0); +  // fillIntArray is a contributed function 
-  fill(col, 0); +  fillIntArray(row, 0); 
-  fill(diag1, 0); +  fillIntArray(col, 0); 
-  fill(diag2, 0);+  fillIntArray(d[0], 0); 
 +  fillIntArray(d[1], 0);
      
-  try(N, row, col, diag1, diag2, 0);+  search(N, row, col, d, 0);
      
-  return 0; 
-} 
- 
-int fill(int[] a, int v) { 
-  int i; 
-   
-  for (i = 0; i < a.length; i = i+1) { 
-    a[i] = v; 
-  } 
   return 0;   return 0;
 } }
Line 42: Line 36:
       }       }
     }     }
-    printLine("");+    printChar('\n');
   }   }
-  printLine("")+  printChar('\n');
-  return 0;+
 } }
  
-int try(int N, int[] row, int[] col, int[] diag1, int[] diag2, int c) {+int search(int N, int[] row, int[] col, int[][] d, int c) {
   int r;   int r;
      
Line 55: Line 48:
   } else {   } else {
     for (r = 0; r < N; r = r+1) {     for (r = 0; r < N; r = r+1) {
-      if (row[r] == 0 && diag1[r+c] == 0 && diag2[r+N-1-c] == 0) { +      if (row[r] == 0 && d[0][r+c] == 0 && d[1][r+N-1-c] == 0) { 
-        row[r] = 1; +        row[r] = d[0][r+c] = d[1][r+N-1-c] = 1;
-        diag1[r+c] = 1+
-        diag2[r+N-1-c] = 1;+
         col[c] = r;         col[c] = r;
-        try(N, row, col, diag1, diag2, c+1); +        search(N, row, col, d, c+1); 
-        row[r] = 0+        row[r] = d[0][r+c] = d[1][r+N-1-c] = 0;
-        diag1[r+c] = 0; +
-        diag2[r+N-1-c] = 0;+
       }       }
     }     }
   }   }
-  return 0; 
 } }
 </code> </code>
 +
 +Note that ''fillIntArray'' is a [[contributed_functions|contributed function]].
the_eight_queens_solver.1329809048.txt.gz · Last modified: 2012/02/21 07:24 by xjia

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki