Example #1
0
 public int totalNQueens(int n) {
   StringBuilder[] board = new StringBuilder[n];
   for (int i = 0; i < n; i++) {
     board[i] = new StringBuilder();
     for (int j = 0; j < n; j++) {
       board[i].append('.');
     }
   }
   for (int i = 0; i < n / 2; i++) {
     board[0].setCharAt(i, 'Q');
     dfs(n, 1, board);
     board[0].setCharAt(i, '.');
   }
   ArrayList<String[]> aux = new ArrayList<String[]>();
   for (String[] k : res) {
     String[] tmp = new String[n];
     for (int i = 0; i < n; i++) {
       StringBuilder sb = new StringBuilder(k[i]).reverse();
       tmp[i] = sb.toString();
     }
     aux.add(tmp);
   }
   res.addAll(aux);
   if (n % 2 != 0) {
     board[0].setCharAt(n / 2, 'Q');
     dfs(n, 1, board);
     board[0].setCharAt(n / 2, '.');
   }
   return res.size();
 }
Example #2
0
 public void solve(InputReader in, OutputWriter out) {
   int n = in.nextInt();
   ArrayList<String> a = new ArrayList<>();
   for (int i = 0; i < n; i++) {
     a.add(in.next());
   }
   TreeNode tree = new TreeNode(a);
   int res = new A1().maxPathSum(tree);
   out.println(res);
 }
Example #3
0
 void constructBoard(StringBuilder[] board) {
   String[] tmp = new String[board.length];
   for (int i = 0; i < board.length; i++) {
     tmp[i] = board[i].toString();
   }
   res.add(tmp);
 }
Example #4
0
 public ArrayList<Integer> morrisTraversal() {
   ArrayList<Integer> res = new ArrayList<>();
   TreeNode current = this;
   while (current != null) {
     if (current.left == null) {
       res.add(current.val);
       current = current.right;
     } else {
       TreeNode pre = current.left;
       while (pre.right != null && pre.right != current) {
         pre = pre.right;
       }
       if (pre.right == null) {
         pre.right = current;
         current = current.left;
       } else {
         pre.right = null;
         res.add(current.val);
         current = current.right;
       }
     }
   }
   return res;
 }
Example #5
0
 public static ArrayList<String> serializeTree(TreeNode tree) {
   ArrayList<String> res = new ArrayList<>();
   LinkedList<TreeNode> queue = new LinkedList<>();
   queue.addLast(tree);
   while (!queue.isEmpty()) {
     TreeNode node = queue.removeFirst();
     if (node == null) {
       res.add(NULL);
     } else {
       res.add(String.valueOf(node.val));
       queue.add(node.left);
       queue.add(node.right);
     }
   }
   while (res.size() > 1 && res.get(res.size() - 1).equals(NULL)) {
     res.remove(res.size() - 1);
   }
   return res;
 }