LeetCode - Backtracking | Set 7 (Sudoku) | GeeksforGeeks


Backtracking | Set 7 (Sudoku) | GeeksforGeeks
Given a partially filled 9×9 2D array ‘grid[9][9]‘, the goal is to assign digits (from 1 to 9) to the empty cells so that every row, column, and subgrid of size 3×3 contains exactly one instance of the digits from 1 to 9.

Before assigning a number, we check whether it is safe to assign. We basically check that the same number is not present in current row, current column and current 3X3 subgrid. After checking for safety, we assign the number, and recursively check whether this assignment leads to a solution or not. If the assignment doesn’t lead to a solution, then we try next number for current empty cell. And if none of number (1 to 9) lead to solution, we return false.
  Find row, col of an unassigned cell
  If there is none, return true
  For digits from 1 to 9
    a) If there is no conflict for digit at row,col
        assign digit to row,col and recursively try fill in rest of grid
    b) If recursion successful, return true
    c) Else, remove digit and try another
  If all digits have been tried and nothing worked, return false

/* Takes a partially filled-in grid and attempts to assign values to
  all unassigned locations in such a way to meet the requirements
  for Sudoku solution (non-duplication across rows, columns, and boxes) */
bool SolveSudoku(int grid[N][N])
{
    int row, col;
    // If there is no unassigned location, we are done
    if (!FindUnassignedLocation(grid, row, col))
       return true; // success!
    // consider digits 1 to 9
    for (int num = 1; num <= 9; num++)
    {
        // if looks promising
        if (isSafe(grid, row, col, num))
        {
            // make tentative assignment
            grid[row][col] = num;
            // return, if success, yay!
            if (SolveSudoku(grid))
                return true;
            // failure, unmake & try again
            grid[row][col] = UNASSIGNED;
        }
    }
    return false; // this triggers backtracking
}
/* Searches the grid to find an entry that is still unassigned. If
   found, the reference parameters row, col will be set the location
   that is unassigned, and true is returned. If no unassigned entries
   remain, false is returned. */
bool FindUnassignedLocation(int grid[N][N], int &row, int &col)
{
    for (row = 0; row < N; row++)
        for (col = 0; col < N; col++)
            if (grid[row][col] == UNASSIGNED)
                return true;
    return false;
}
/* Returns a boolean which indicates whether any assigned entry
   in the specified row matches the given number. */
bool UsedInRow(int grid[N][N], int row, int num)
{
    for (int col = 0; col < N; col++)
        if (grid[row][col] == num)
            return true;
    return false;
}
/* Returns a boolean which indicates whether any assigned entry
   in the specified column matches the given number. */
bool UsedInCol(int grid[N][N], int col, int num)
{
    for (int row = 0; row < N; row++)
        if (grid[row][col] == num)
            return true;
    return false;
}
/* Returns a boolean which indicates whether any assigned entry
   within the specified 3x3 box matches the given number. */
bool UsedInBox(int grid[N][N], int boxStartRow, int boxStartCol, int num)
{
    for (int row = 0; row < 3; row++)
        for (int col = 0; col < 3; col++)
            if (grid[row+boxStartRow][col+boxStartCol] == num)
                return true;
    return false;
}
/* Returns a boolean which indicates whether it will be legal to assign
   num to the given row,col location. */
bool isSafe(int grid[N][N], int row, int col, int num)
{
    /* Check if 'num' is not already placed in current row,
       current column and current 3x3 box */
    return !UsedInRow(grid, row, num) &&
           !UsedInCol(grid, col, num) &&
           !UsedInBox(grid, row - row%3 , col - col%3, num);
}

http://www.cnblogs.com/TenosDoIt/p/3800485.html
    void solveSudoku(vector<vector<char> > &board) {
        for(int i = 0; i < 9; i++)
            for(int j = 0; j < 9; j++)
                if(board[i][j] != '.')
                    fill(i, j, board[i][j] - '0');
        solver(board, 0);
    }
     
    bool solver(vector<vector<char> > &board, int index)
    {// 0 <= index <= 80,index表示接下来要填充第index个格子
        if(index > 80)return true;
        int row = index / 9, col = index - 9*row;
        if(board[row][col] != '.')
            return solver(board, index+1);
        for(int val = '1'; val <= '9'; val++)//每个为填充的格子有9种可能的填充数字
        {
            if(isValid(row, col, val-'0'))
            {
                board[row][col] = val;
                fill(row, col, val-'0');
                if(solver(board, index+1))return true;
                clear(row, col, val-'0');
            }
        }
        board[row][col] = '.';//注意别忘了恢复board状态
        return false;
    }
     
    //判断在第row行col列填充数字val后,是否是合法的状态
    bool isValid(int row, int col, int val)
    {
        if(rowValid[row][val] == 0 &&
           columnValid[col][val] == 0 &&
           subBoardValid[row/3*3+col/3][val] == 0)
           return true;
        return false;
    }
     
    //更新填充状态
    void fill(int row, int col, int val)
    {
        rowValid[row][val] = 1;
        columnValid[col][val] = 1;
        subBoardValid[row/3*3+col/3][val] = 1;
    }
     
    //清除填充状态
    void clear(int row, int col, int val)
    {
        rowValid[row][val] = 0;
        columnValid[col][val] = 0;
        subBoardValid[row/3*3+col/3][val] = 0;
    }
private:
    int rowValid[9][10];//rowValid[i][j]表示第i行数字j是否已经使用
    int columnValid[9][10];//columnValid[i][j]表示第i列数字j是否已经使用
    int subBoardValid[9][10];//subBoardValid[i][j]表示第i个小格子内数字j是否已经使用
};
http://bangbingsyb.blogspot.com/2014/11/leetcode-valid-sudoku-sudoku-solver.html
    void solveSudoku(vector<vector<char> > &board) {
        if(board.size()<9 || board[0].size()<9) return;
        bool findSol = solSudoku(board, 0, 0);
    }
    
    bool solSudoku(vector<vector<char>> &board, int irow, int icol) {
        if(irow==9) return true;
        
        int irow2, icol2;
        if(icol==8) {
            irow2 = irow+1;
            icol2 = 0;
        }
        else {
            irow2 = irow;
            icol2 = icol+1;
        }
        
        if(board[irow][icol]!='.') {
            if(!isValid(board, irow, icol)) return false;
            return solSudoku(board, irow2, icol2);
        }
        
        for(int i=1; i<=9; i++) {
            board[irow][icol] = '0'+i;
            if(isValid(board, irow, icol) && solSudoku(board, irow2, icol2)) return true;
        }
        
        // reset grid 
        board[irow][icol] = '.';
        return false;
    }
    
    bool isValid(vector<vector<char>> &board, int irow, int icol) {
        char val = board[irow][icol];
        if(val-'0'<1 || val-'0'>9) return false;
        
        // check row & col
        for(int i=0; i<9; i++) {
            if(board[irow][i]==val && i!=icol) return false;
            if(board[i][icol]==val && i!=irow) return false;
        }
        
        //check 3x3 box
        int irow0 = irow/3*3;
        int icol0 = icol/3*3;
        for(int i=irow0; i<irow0+3; i++) {
            for(int j=icol0; j<icol0+3; j++) {
                if(board[i][j]==val && (i!=irow || j!=icol)) return false;
            }
        }
        
        return true;
    }
http://blog.csdn.net/linhuanmars/article/details/20748761
http://www.cnblogs.com/zhuli19901106/p/3574405.html
Total time complexity is O((n^2)!), but it would never appear that large. Space complexity is O(n^2)
The Dancing Links Algorithm seems to be a very exquisite way to solve Sudoku, but here it might be way too complicated for an interview question.
Java Solution from EPI

Implement a Sudoku solver SudokuSolve.java

  public static boolean solveSudoku(int[][] A) {
    if (!isValidSudoku(A)) {
      System.out.println("Initial configuration violates constraints.");
      return false;
    }

    if (solveSudokuHelper(A, 0, 0)) {
      for (int[] element : A) {
        System.out.println(Arrays.toString(element));
      }
      return true;
    } else {
      System.out.println("No solution exists.");
      return false;
    }
  }

  private static boolean solveSudokuHelper(int[][] A, int i, int j) {
    if (i == A.length) {
      i = 0; // Starts a new row.
      if (++j == A[i].length) {
        return true; // Entire matrix has been filled without conflict.
      }
    }

    // Skips nonempty entries.
    if (A[i][j] != 0) {
      return solveSudokuHelper(A, i + 1, j);
    }

    for (int val = 1; val <= A.length; ++val) {
      // Note: practically, it's substantially quicker to check if entry val
      // conflicts with any of the constraints if we add it at (i,j) before
      // adding it, rather than adding it and then calling isValidSudoku.
      // The reason is that we are starting with a valid configuration,
      // and the only entry which can cause a problem is entryval at (i,j).
      if (validToAdd(A, i, j, val)) {
        A[i][j] = val;
        if (solveSudokuHelper(A, i + 1, j)) {
          return true;
        }
      }
    }

    A[i][j] = 0; // Undo assignment.
    return false;
  }

  private static boolean validToAdd(int[][] A, int i, int j, int val) {
    // Check row constraints.
    for (int[] element : A) {
      if (val == element[j]) {
        return false;
      }
    }

    // Check column constraints.
    for (int k = 0; k < A.length; ++k) {
      if (val == A[i][k]) {
        return false;
      }
    }

    // Check region constraints.
    int regionSize = (int) Math.sqrt(A.length);
    int I = i / regionSize, J = j / regionSize;
    for (int a = 0; a < regionSize; ++a) {
      for (int b = 0; b < regionSize; ++b) {
        if (val == A[regionSize * I + a][regionSize * J + b]) {
          return false;
        }
      }
    }
    return true;
  }
todo:http://n00tc0d3r.blogspot.com/2013/06/sudoku-solver.html
 // For each cell, populate an array of candidate numbers.
 // Return the cell with least number of candidates.
 private Pair<Integer, Integer> init(char[][] board, HashMap<Pair<Integer, Integer>, HashSet<Integer>> cand) {
   // collect existing numbers
   ArrayList<ArrayList<Integer>> numbersInRow = new ArrayList<ArrayList<Integer>>();
   ArrayList<ArrayList<Integer>> numbersInCol = new ArrayList<ArrayList<Integer>>();
   ArrayList<ArrayList<Integer>> numbersInBox = new ArrayList<ArrayList<Integer>>();
   for (int i=0; i<9; ++i) {
     ArrayList<Integer> row = new ArrayList<Integer>(); // row i
     ArrayList<Integer> col = new ArrayList<Integer>(); // column i
     for (int j=0; j<9; ++j) {
       if (board[i][j] != '.') row.add(board[i][j]-'0');
       if (board[j][i] != '.') col.add(board[j][i]-'0');
     }
     numbersInRow.add(row);
     numbersInCol.add(col);
   }
   for (int i=0; i<9; i+=3) {
     for (int j=0; j<9; j+=3) {
       ArrayList<Integer> box = new ArrayList<Integer>(); // box i
       for (int r=i; r<i+3; ++r) {
         for (int c=j; c<j+3; ++c) {
           if (board[r][c] != '.') box.add(board[r][c]-'0');
         }
       }
       numbersInBox.add(box);
     }
   }
   // initialize with all empty cells
   int minSet = 10;
   Pair<Integer, Integer> minCell = null;
   for (int i=0; i<9; ++i) {
     int boxR = (i/3) * 3;
     for (int j=0; j<9; ++j) {
       if (board[i][j] == '.') {
         Pair<Integer, Integer> cell = new Pair<Integer, Integer>(i, j);
         HashSet<Integer> set = new HashSet<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9));
         set.removeAll(numbersInRow.get(i));
         set.removeAll(numbersInCol.get(j));
         set.removeAll(numbersInBox.get(boxR + j/3));
         cand.put(cell, set);
         if (set.size() < minSet) {
           minCell = cell; minSet = set.size();
         }
       }
     }
   }
   return minCell;
 }
 
 // Fill in the given cell with the given value and update candidate sets of same row/column/box.
 // Return the cell with least number of candidates. If a conflict is detected, return the given cell.
 private Pair<Integer, Integer> fillOneCell(char[][] board,
     Pair<Integer, Integer> cell, int num,
     ArrayList<Pair<Integer, Integer>> touched,
     HashMap<Pair<Integer, Integer>, HashSet<Integer>> cand) {
   board[cell.first][cell.second] = (char)('0' + num);
   int minSet = 10;
   Pair<Integer, Integer> minCell = null;
   // resolve conflicts
   for (Pair<Integer, Integer> c : cand.keySet()) {
     if (c.first == cell.first || c.second == cell.second
         || ((c.first/3) == (cell.first/3) && (c.second/3) == (cell.second/3))) {
       if (cand.get(c).remove(num)) {
         touched.add(c);
         if (cand.get(c).isEmpty()) return cell;
       }
     }
     if (minCell == null || cand.get(c).size() < minSet) {
       minCell = c; minSet = cand.get(c).size();
     }
   }
   return minCell;
 }
 
 // Recursively solve a Sudoku.
 // Return true if the current board is a valid Sudoku (could be partially filled).
 private boolean solveSudokuHelper(char[][] board, Pair<Integer, Integer> cell,
     HashMap<Pair<Integer, Integer>, HashSet<Integer>> cand) {
   if (cand.isEmpty()) return true;
   HashSet<Integer> set = cand.get(cell);
   cand.remove(cell);
   for (Integer num : set) { // try each candidate value
     ArrayList<Pair<Integer, Integer>> touched = new ArrayList<Pair<Integer, Integer>>();
     Pair<Integer, Integer> minCell = fillOneCell(board, cell, num, touched, cand);
     // try next cell
     if (!cell.equals(minCell) && solveSudokuHelper(board, minCell, cand)) return true;
     // recover
     for (Pair<Integer, Integer> cc : touched) {
       cand.get(cc).add(num);
     }
   }
   cand.put(cell, set);
   return false;
 }
 
 public void solveSudoku(char[][] board) {
   HashMap<Pair<Integer, Integer>, HashSet<Integer>> cand =
       new HashMap<Pair<Integer, Integer>, HashSet<Integer>>();
   Pair<Integer, Integer> cell = init(board, cand);
   solveSudokuHelper(board, cell, cand);
 }
Read full article from Backtracking | Set 7 (Sudoku) | GeeksforGeeks

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts