My code is correct in eclipse. But it is wrong when i put it to OJ


  • 0
    A

    The main idea is to set up some arrays keep the place that has been occupied by queen and use a backtracking method to get all solutions.

    import java.util.Arrays;
    
    public class Solution {
        public static void main(String[] args) {
        	System.out.print(new Solution().totalNQueens(8));
        }
        static int result = 0;
        public int totalNQueens(int n) {
            int[] row = new int[n];/*row represent the row which has been occupied*/
            int[] col = new int[n];/*col represent the col which has been occupied*/
            int[] biasl = new int[2*n-1];
            int[] biasr = new int[2*n-1];/*biasl and biasl  represent the bials which have been occupied*/
            Arrays.fill(row, 0);
            Arrays.fill(col, 0);
            Arrays.fill(biasl, 0);
            Arrays.fill(biasr, 0);/*initiate all arrays*/
            launch(row, col, biasl, biasr, 0,n);
            return result;
        }
        private void launch(int[] row, int[] col, int[] biasl, int[] biasr, int x,int n) {
            /*x represents the row which should been put in queen*/
            for(int j = 0;j < n;j++) {
                if(row[x] == 1 || col[j] == 1 || biasl[x+j] == 1 || biasr[x-j+n-1] == 1) {
            /*if there's a queen has occupied the row or col or bias,then continue*/
                        continue;
                } else if(x == n-1) {
            /*if it's the last row,we have get one validate solution*/
                    result++;
                } else {
                    row[x] = 1;
                    col[j] = 1;
                    biasl[x+j] = 1;
                    biasr[x-j+n-1] = 1;
                    launch(row, col, biasl, biasr, x+1,n);
                    row[x] = 0;
                    col[j] = 0;
                    biasl[x+j] = 0;
                    biasr[x-j+n-1] = 0;
           /*backtracking*/
                }
            }
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.