title: How can I speed up my n*n sudoku grid generator?
body: <p>This is my code for a Sudoku-style grid generator. It generates every possible different n*n grid where there cannot be the same number in a certain column or row (like a sudoku) and also counts how many different combinations there are. E.g. one example of a 3*3 grid could be:</p>
  
  <p>[ 3, 2, 1 ]</p>
  
  <p>[ 1, 3, 2 ]</p>
  
  <p>[ 2, 1, 3 ]</p>
  
  <p>Unfortunately, for anything past 4*4 grids, it takes too long to do this, therefore, could anybody help me edit this slightly so that it is much faster?</p>
  
  <pre><code>import java.util.Arrays;
  
  public class GridN {
  
  public static final int SIZE = 3;
  
  public static int count;
  
  public static void main(String[] args) {
      int[][] grid = new int[SIZE][SIZE];
      count = 0;
      bruteSolve(0, 0, grid);
  }
  
  public static void bruteSolve(int num1, int num2, int[][] grid) {
      for (int i = 1; i &lt; SIZE + 1; i++) {
          grid[num1][num2] = i;
          if (num2 == SIZE - 1 &amp;&amp; num1 == SIZE - 1) {
              if (isValid(grid)) {
                  count++;
                  System.out.println(Arrays.deepToString(grid));
                  System.out.println(count);
              }
          } else if (num2 == SIZE - 1) {
              bruteSolve(num1 + 1, 0, grid);
          } else {
              bruteSolve(num1, num2 + 1, grid);
          }
      }
  }
  
  public static boolean isValid(int[][] grid) {
      int factorial = 1;
      int fibonacci = 0;
      int totalX1 = 1;
      int totalY1 = 1;
      int totalX2 = 0;
      int totalY2 = 0;
  
      for (int i = SIZE; i &gt; 0; i--) {
          factorial = factorial * i;
      }
      for (int i = SIZE; i &gt; 0; i--) {
          fibonacci = fibonacci + i;
      }
  
      for (int i = 0; i &lt; SIZE; i++) {
          for (int j = 0; j &lt; SIZE; j++) {
              totalY1 = totalY1 * grid[i][j]; // checks all columns
              totalX1 = totalX1 * grid[j][i]; // checks all rows
              totalX2 = totalX2 + grid[j][i];
              totalY2 = totalY2 + grid[i][j];
          }
          if (totalX1 != factorial || totalY1 != factorial
                  || totalX2 != fibonacci || totalY2 != fibonacci) {
              return false;
          }
          totalX1 = 1;
          totalY1 = 1;
          totalX2 = 0;
          totalY2 = 0;
      }
      return true;
  }
  
  }
  </code></pre>