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

LeetCode Sudoku Solver

时间:2015-03-02 14:53:12      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

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...

技术分享

题意:数独游戏

思路:回溯解决,是不是好久没写了,开标记数组老是错

class Solution {
	public:
		bool check(vector<vector<char> > &board, int position) {
			int x = position / 9;
			int y = position % 9;
			for (int i = 0; i < 9; i++)  
				if (i != x && board[i][y] == board[x][y])  
					return false;  
			for (int j = 0; j < 9; j++)  
				if (j != y && board[x][j] == board[x][y])  
					return false;  
			for (int i = x / 3 * 3; i < (x / 3 + 1) * 3; i++)  
				for (int j = y / 3 * 3; j < (y / 3 + 1) * 3; j++)  
					if (i != x && j != y && board[i][j] == board[x][y])  
						return false;  
			return true;  
		}

		bool solve(vector<vector<char> > &board, int position) {
			if (position == 81)
				return true;

			int row = position / 9;
			int col = position % 9;
			if (board[row][col] == '.') {
				for (int i = 1; i <= 9; i++) {
					board[row][col] = i + '0';
					if (check(board, position) && solve(board, position+1))
						return true;
					board[row][col] = '.';
				}
			}
			else {
				if (solve(board, position + 1))
					return true;
			}
			return false;
		}

		void solveSudoku(vector<vector<char> > &board) {
			solve(board, 0);
		}
};



LeetCode Sudoku Solver

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/44017493

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