标签:
https://leetcode.com/problems/sudoku-solver/
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character ‘.‘
.
You may assume that there will be only one unique solution.
A sudoku puzzle...
...and its solution numbers marked in red.
dfs回朔。。
class Solution { public: static const int N = 9; int cnt; struct Node { int x, y; Node() {} Node(int i, int j) :x(i), y(j) {} }st[N * N]; void solveSudoku(vector<vector<char>>& board) { cnt = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (board[i][j] == ‘.‘) { st[cnt++] = Node(i, j); } } } dfs(board, 0); } bool dfs(vector<vector<char>>& board, int t) { if (t == cnt) return true; for (int i = 1; i <= N; i++) { int x = st[t].x, y = st[t].y; if (isOk(board, x, y, i + ‘0‘)) { board[x][y] = i + ‘0‘; if (dfs(board, t + 1)) return true; board[x][y] = ‘.‘; } } return false; } bool isOk(vector<vector<char>>& board, int x, int y, char ch) { for (int i = 0; i < N; i++) { if (board[x][i] == ch || board[i][y] == ch) return false; } for (int i = x / 3 * 3; i <= x / 3 * 3 + 2; i++) { for (int j = y / 3 * 3; j <= y / 3 * 3 + 2; j++) { if (board[i][j] == ch) return false; } } return true; } };
标签:
原文地址:http://www.cnblogs.com/GadyPu/p/5040166.html