码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode Sudoku Solver

时间:2015-12-11 22:14:33      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

题目连接

https://leetcode.com/problems/sudoku-solver/  

Sudoku Solver

Description

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;
	}
};

leetcode Sudoku Solver

标签:

原文地址:http://www.cnblogs.com/GadyPu/p/5040166.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!