判断valid,没有更好的方法,只能brute force。

 class Solution {
public:
bool isValidSudoku(vector<vector<char> > &board) { int n;
for (int i = ; i < ; ++i) {
vector<bool> contained(, false);
for (int j = ; j < ; ++j) {
if (board[i][j] == '.') continue;
n = board[i][j] - '' - ;
if (contained[n]) return false;
contained[n] = true;
}
} for (int i = ; i < ; ++i) {
vector<bool> contained(, false);
for (int j = ; j < ; ++j) {
if (board[j][i] == '.') continue;
n = board[j][i] - '' - ;
if (contained[n]) return false;
contained[n] = true;
}
} for (int i = ; i < ; ++i) {
for (int j = ; j < ; ++j) {
vector<bool> contained(, false);
for (int k = ; k < ; ++k) {
for (int m = ; m < ; ++m) {
if (board[i*+k][j*+m] == '.') continue;
n = board[i*+k][j*+m] - '' - ;
if (contained[n]) return false;
contained[n] = true;
}
}
}
}
return true;
}
};

求解决方案也只有backtrack。

 class Solution {
public:
void solveSudoku(vector<vector<char> > &board) {
list<int> unsolved;
getUnsolved(board, unsolved);
recursive(board, unsolved);
} bool recursive(vector<vector<char> > &board, list<int> &unsolved) {
if (unsolved.empty()) return true;
int loc = unsolved.front();
int row = loc / ;
int col = loc % ; vector<bool> contained(, false);
int n;
for (int i = ; i < ; ++i) {
if (board[row][i] != '.') {
contained[board[row][i] - '' - ] = true;
}
if (board[i][col] != '.') {
contained[board[i][col] - '' - ] = true;
}
} row = row / ; col = col / ;
for (int i = ; i < ; ++i) {
for (int j = ; j < ; ++j) {
if (board[row * + i][col * + j] != '.') {
contained[board[row * + i][col * + j] - '' - ] = true;
}
}
} row = loc / ; col = loc % ;
for (int i = ; i < ; ++i) {
if (!contained[i]) {
board[row][col] = i + + '';
unsolved.pop_front();
if (recursive(board, unsolved)) return true;
board[row][col] = '.';
unsolved.push_front(loc);
}
} return false;
} void getUnsolved(vector<vector<char> > &board, list<int> &unsolved) {
for (int i = ; i < ; i++) {
for (int j = ; j < ; ++j) {
if (board[i][j] == '.') {
unsolved.push_back(i * + j);
}
}
}
}
};

用unsolved数组可以避免每次都需要从头扫到尾去找下一个元素。

用contained数组先保存了在该行该格该九宫格里已经存在的数字。这样就可以直接去试验剩下的数字,而不需要每次都再检查一遍插入的值是否合法。

backtrack是一个要有返回值,否则都不知道你backtrack到头了没,是否找到解决方案了。

最新文章

  1. zk 起别名时候碰到的问题
  2. 浅谈T-SQL中的子查询
  3. webform简单控件
  4. 5.6 WebDriver API实例讲解(31-35)
  5. 注册表 锁IE首页
  6. &lt;select&gt;改造成&lt;s:select&gt;实现表单的回显功能
  7. nandsim ubi nand nor
  8. u3d shader使用
  9. 2015第6周三ztree的使用
  10. 【剑指offer】q50:树节点最近的祖先
  11. jquery 重复事件
  12. 表单验证 jquery-validation
  13. 开发MOSS自定义字段类型
  14. Vue浅谈
  15. Maven - Maven基础
  16. __x__(39)0909第五天__ 表格 table
  17. C# 多线程及同步简介示例
  18. php通过CURL模拟get提交请求
  19. 图解android开发在界面上显示图片
  20. Ubuntu14.04 64bit 编译安装nginx1.7+php5.4+mysql5.6

热门文章

  1. ActionBarSherlock的使用——(一)配置
  2. Android实现网络音乐播放器
  3. ***CI新增记录成功后的返回值判断,是用isset还是empty
  4. Lucene实践
  5. SAE Java开发问题汇总
  6. Android 饼状图收集
  7. eclipse下导入工程的小问题
  8. Spotlight on MySQL监控MySQL服务器
  9. php升级5.3到5.4,5.5,5.6
  10. LIS(nlogn) POJ 3903 Stock Exchange