GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode/NQueensII.java at master · mengli/leetcode Expand file tree/ Copy pathNQueensII.javaMore file actions 50 lines (49 loc) · 1.34 KB / Copy pathNQueensII.javaFile metadata and controls50 lines (49 loc) · 1.34 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 /** * Follow up for N-Queens problem. * * <p>Now, instead outputting board configurations, return the total number of distinct solutions. */ public class NQueensII { public int solveNQueens(int n) { if (n == 0) return 0; StringBuffer line = new StringBuffer(); for (int i = 0; i < n; i++) { line.append('.'); } StringBuffer[] sol = new StringBuffer[n]; for (int i = 0; i < n; i++) { sol[i] = new StringBuffer(line.toString()); } boolean[] cols = new boolean[n]; int[] row = new int[n]; int[] count = new int[1]; findSolutions(n, 0, sol, row, cols, count); return count[0]; } private void findSolutions( int n, int start, StringBuffer[] sol, int[] row, boolean[] cols, int[] count) { if (start == n) { count[0]++; } else { for (int i = 0; i < n; i++) { if (cols[i]) continue; boolean ok = true; for (int j = 0; j < start; j++) { if (Math.abs(start - j) == Math.abs(i - row[j])) { ok = false; break; } } if (ok) { cols[i] = true; sol[start].setCharAt(i, 'Q'); row[start] = i; findSolutions(n, start + 1, sol, row, cols, count); row[start] = 0; sol[start].setCharAt(i, '.'); cols[i] = false; } } } } } |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |