Leetcode Sudoku Solver

思路

1. 典型的深搜题

2. 框架 dfs(board, ith)

代码

#include <iostream>
#include <stdio.h>
#include <memory.h>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <deque>
#include <cstring>
#define MIN(x,y) (x)<(y)?(x):(y)
#define MAX(x,y) (x)>(y)?(x):(y)
using namespace std;

bool IsValid(vector<vector<char> > &board, int x, int y, int v)  {
		int size_row = board.size();
  		int size_col = board[0].size();

  		for(int i = 0; i < size_col; i ++)  {
  			if(board[x][i] == v+'0') return false;
  		}

  		for(int j = 0; j < size_row; j ++)  {
  			if(board[j][y] == v + '0') return false;
  		}

  		// x, y 
  		for(int i = 0; i < 3; i ++)  {
  			for(int j = 0; j < 3; j ++)  {
  				int newx = (x/3)*3 + i;
  				int newy = (y/3)*3 + j;

  				if(board[newx][newy] == '0' + v) 
  					return false;
  			}
  		}
}

void PrintMatrix(vector<vector<char> > &board)  {
	int size_row = board.size();
	int size_col = board[0].size();

	for(int i = 0; i < size_row; i ++)  {
		for(int j = 0; j < size_col; j ++)  {
			cout << board[i][j] << " ";
		}
		cout << endl;
	}
}

bool found;
void dfs(vector<vector<char> > &board, int ith)  {
	int size_row = board.size();
	int size_col = board[0].size();

	if(ith == size_col*size_row) {
		found = true;
		return;
	}

	if(found) return;

	int newx = ith / size_col;
	int newy = ith - (ith / size_col) * size_col;

	if(board[newx][newy] != '.')  {
		dfs(board, ith+1);
	}  else  {
		for(int v = 1; v <= 9 && !found; v ++)  {
			if(IsValid(board, newx, newy, v))  {
				board[newx][newy] = v+'0';
				dfs(board, ith+1);
				if(found) return;
				board[newx][newy] = '.';
			}
		}
	}
}



class Solution {
public:
    void solveSudoku(vector<vector<char> > &board) {
  		found = false;
  		dfs(board, 	0);
    }
};

int main() {	
	string matrix[9] = {"..9748...","7........",".2.1.9...","..7...24.",".64.1.59.",".98...3..","...8.3.2.","........6","...2759.." };
	vector<vector<char> > board;
	
	for(int i = 0; i < 9; i ++)  {
		vector<char> tmp(matrix[i].c_str(), matrix[i].c_str()+9);
		board.push_back(tmp);
	}

	//PrintMatrix(board);
	Solution so;
	so.solveSudoku(board);
	PrintMatrix(board);
	return 0;
}

  

原文地址:https://www.cnblogs.com/zhouzhuo/p/3688387.html