leetcode hard模式专杀之37. Sudoku Solver

来源:互联网 发布:c json ignore 编辑:程序博客网 时间:2024/05/17 08:33

继续刷题leetcode之hard模式

这题乍一看挺吓人的 ,不过正好前几个礼拜做过八皇后问题,对回溯法有一定的记忆和认知,然后还有的技巧是位运算,hashmap记录等等,尽可能地节省空间复杂度。思路如下,先遍历一遍二维数组,本次遍历是为了收集统计数据,哪些统计数据呢?有三个,第一,每一行还差哪些数字没填, 第二,每一列还有哪些数字没填,第三,每个block还有哪些数字没填,为了节省空间,那些数字没填就交给位运算的东西去做把,理论上只需要9个位就可以标记一行或者一列有那些数字没填,这个不用我多解释了吧?已有的就用0表示,没有的就用1表示。用比特map不仅可以节省空间,更重要的是还可以通过位运算做集合的并集操作,这也是大大节省时间复杂度的。


这里有个坑要注意的是,题目的输入是char[][],也就是是char型,适当的时候要注意转换成int型,而有时又需要从int型转回char型,为了方便,我直接写了两个函数来做这种处理。


有了以上基础以后,思路大概如下,找到第一个空位置,开始尝试该位置可能的值,可能的值由以上三个可能值集合求交集而来,接下来就是回溯发来,成功就往下走,失败就返回并恢复参数,注意恢复参数很重要,不然失败的子函数就会影响到下一次递归。


代码如下:


public class Solution {    public int getBlockIndex(int rowIndex, int colIndex){        return 3*(rowIndex/3)+(colIndex/3);    }    public int char2int(char a){        return (int)a-48;    }    public char int2char(int i){        return (char)(i+48);    }    public void solveSudoku(char[][] board) {        Map<Integer,Integer> rowSet = new HashMap<>();        Map<Integer,Integer> colSet = new HashMap<>();        Map<Integer,Integer> blockSet = new HashMap<>();        // initialization        for(int k = 0; k<9; k++){            rowSet.put(k, (int)Math.pow(2,9)-1);            colSet.put(k, (int)Math.pow(2,9)-1);            blockSet.put(k, (int)Math.pow(2,9)-1);        }        //after this, statistics are collected        for(int row=0;row<board.length;row++){            for(int col=0;col<board[row].length;col++){                if(board[row][col]=='.'){                    continue;                }                rowSet.put(row,rowSet.get(row) & ~(1 << char2int(board[row][col])-1));                colSet.put(col,colSet.get(col) & ~(1 << char2int(board[row][col])-1));                blockSet.put(getBlockIndex(row,col),blockSet.get(getBlockIndex(row,col)) & ~(1 << char2int(board[row][col])-1));            }        }        for(int row=0;row<board.length;row++) {            for (int col = 0; col < board[row].length; col++) {                if(board[row][col]!='.'){                    continue;                }                int options = (rowSet.get(row) & colSet.get(col) & blockSet.get(getBlockIndex(row, col)));                enumerate(board, row, col, rowSet, colSet, blockSet, options);                // has to break here because enumerate can handle all, we only need to enumerate from the first '.' character                break;            }        }    }    private static class Position{        int row;        int col;        public Position(int row, int col) {            this.row = row;            this.col = col;        }    }    public Position nextPosition(char[][] board, int row, int col){        if(col<board[0].length-1){            return new Position(row, col+1);        }else{            if(row<board.length-1){                return new Position(row+1, 0);            }else{                return null;            }        }    }    public Position nextEmptyCel(char[][] board, int row, int col){        Position position = nextPosition(board, row, col);        while(position!=null){            if(board[position.row][position.col]=='.'){                return position;            }            position = nextPosition(board, position.row, position.col);        }        return  null;    }    public boolean enumerate(char[][] board, int row, int col, Map<Integer,Integer> rowSet, Map<Integer,Integer> colSet, Map<Integer,Integer> blockSet, int options){        if(board[row][col]!='.'){            return false;        }        // no option to try, means fail        if(options==0){            return false;        }        char originBoardValue;        int originRowSetValue;        int originColSetValue;        int originBlockSetValue;        //extract positions from options        for(int i = 0; i<9; i++){            if(((options >> i) & 1) ==1){                int pos = i+1;                //try with value pos in row, col                originBoardValue = board[row][col];  //backup                board[row][col] = int2char(pos);                //update rowSet                originRowSetValue = rowSet.get(row);                rowSet.put(row,rowSet.get(row) & ~(1 << pos-1));                //update colSet                originColSetValue = colSet.get(col);                colSet.put(col,colSet.get(col) & ~(1 << pos-1));                //update blockSet                originBlockSetValue = blockSet.get(getBlockIndex(row, col));                blockSet.put(getBlockIndex(row, col),blockSet.get(getBlockIndex(row,col)) & ~(1 << pos-1));                //enumerate next (row,col) with '.' value, and calculate its options                Position next = nextEmptyCel(board, row, col);                if(next==null){                    return true;                }                int nextRow = next.row;                int nextCol = next.col;                int newOptions = (rowSet.get(nextRow) & colSet.get(nextCol) & blockSet.get(getBlockIndex(nextRow, nextCol)));                if(enumerate(board, nextRow,nextCol, rowSet, colSet, blockSet, newOptions)){                    return true;                }else{                    //recover sets and continue;                    board[row][col]=originBoardValue;                    rowSet.put(row,originRowSetValue);                    colSet.put(col, originColSetValue);                    blockSet.put(getBlockIndex(row, col), originBlockSetValue);                }            }        }        return false;    }}


原创粉丝点击