求助大佬,为什么没输出
  • 板块P1784 数独
  • 楼主ttltony
  • 当前回复0
  • 已保存回复0
  • 发布时间2022/8/4 12:24
  • 上次更新2023/10/27 17:05:16
查看原帖
求助大佬,为什么没输出
709380
ttltony楼主2022/8/4 12:24
#include <cstdio>

using namespace std;

int Map[10][10], position[][4] = {{0, 0, 0, 0}, {0, 1, 2, 3}, {0, 4, 5, 6}, {0, 7, 8, 9}};

int getx(int x) {
    for (int i = 1; i <= 3; i ++ ) for (int j = 1; j <= 3; j ++ ) if (position[i][j] == x) return i;
}

int gety(int y) {
    for (int i = 1; i <= 3; i ++ ) for (int j = 1; j <= 3; j ++ ) if (position[i][j] == y) return i;
}

bool check1(int num, int x, int y) {
    for (int i = (x - 1) * 3 + 1; i <= x * 3; i ++ ) for (int j = (y - 1) * 3 + 1; j <= y * 3; j ++ ) {
            if (i == x && j == y) continue;
            if (Map[i][j] == num) return false;
        }
    return true;
}

bool check2(int num, int x, int y) {
	for (int i = x + 1; i <= 9; i ++ ) if (Map[i][y] == num) return false;
	for (int i = x - 1; i >= 1; i -- ) if (Map[i][y] == num) return false;
	return true;
}

bool check3(int num, int x, int y) {
	for (int i = y + 1; i <= 9; i ++ ) if (Map[x][i] == num) return false;
	for (int i = y - 1; i >= 1; i -- ) if (Map[x][i] == num) return false;
}

void print() {
	for (int i = 1; i <= 9; i ++ ) {
		for (int j = 1; j <= 9; j ++ ) printf("%d ", Map[i][j]);
		printf("\n");
	}
}

void dfs(int x, int y) {
    if (Map[x][y] != 0) return ;
    for (int i = 1; i <= 9; i ++ ) {
        int tx = getx(x), ty = gety(y);
        if (!check1(i, tx, ty)) continue;
        else if (!check2(i, x, y)) continue;
        else if (!check3(i, x, y)) continue;
        else {
        	Map[x][y] = i;
        	if (x + 1 <= 9) dfs(x + 1, y);
        	else if (y + 1 <= 9) dfs(x, y + 1);
        	else {
        		print();
        		return ;
			}
		}
    }
}

int main() {
    for (int i = 1; i <= 9; i ++ ) for (int j = 1; j <= 9; j ++ ) scanf("%d", &Map[i][j]);
    for (int i = 1; i <= 9; i ++ ) for (int j = 1; j <= 9; j ++ ) if (!Map[i][j]) dfs(i, j);
    return 0;
}

代码通俗易懂,请多多指教

2022/8/4 12:24
加载中...