POJ 1321 棋盤問題(C)回溯

Emmm,我又來 POJ 了,這題感受比上次作的簡單點。相似皇后問題。可是稍微作了一點變形,好比棋子數量是不定的。棋盤形狀不在是方形等等。web

題目連接:POJ 1321 棋盤問題svg


解題思路

基本思路:從上往下放旗子,每種狀況完成後,覆盤繼續下一種狀況。函數

這裏講一下,void backTrack(int left, int x) 函數。spa

left 表示還剩的棋子數量,顯然若是 left 爲 0,說明全部棋子已放完,那麼方案數 solution 加 1。code

若是不爲 0。那麼繼續檢查當前位置的列是否有棋子,若是無棋子,那麼當前位置能夠放旗子。而後繼續遞歸,棋子數量減 1,行數加 1。若是有棋子,那麼悔棋 1 步。繼續下一個位置。xml

C代碼

/** * @author wowpH * @date 2019-9-14 19:54:16 */
#include<stdio.h>
#include<string.h>

#define TRUE 1
#define FALSE 0

#define MAX_N 8 // 矩陣最大爲8

#define BOARD TRUE // 棋盤
#define BLANK FALSE // 空白

int matrix[MAX_N][MAX_N];// 矩陣,BOARD表示棋盤,BLANK表示空白

int n, k, solution;// solution最終結果

int column[MAX_N];// 每列是否有棋子,TRUE表示有棋子,FALSE表示無棋子

void backTrack(int left, int x) {// 回溯,left表示剩餘棋子,x表示當前行
	if (left == 0) {// 無多餘棋子
		++solution;	// 方案數加1
		return;
	}

	// 遍歷x行及下方的棋盤
	for (int i = x; i < n; ++i) {
		for (int j = 0; j < n; ++j) {
			if (matrix[i][j] == BLANK) {// 空白
				continue;				// 不能放旗子
			}
			if (column[j] == TRUE) {// 第j列有棋子
				continue;			// 不能放旗子
			}

			column[j] = TRUE;			// 當前位置能夠放子,設爲TRUE
			backTrack(left - 1, i + 1);	// 回溯,棋子數減1,行數加1
			column[j] = FALSE;			// 覆盤,設爲無子
		}
	}
}

int main() {
	while (scanf("%d %d", &n, &k) && n != -1 && k != -1) {
		getchar();// '\n'

		// 輸入棋盤
		for (int i = 0; i < n; ++i) {
			for (int j = 0; j < n; ++j) {
				char ch = getchar();
				if (ch == '.') {
					matrix[i][j] = BLANK;// 空白
				} else if (ch == '#') {
					matrix[i][j] = BOARD;// 棋盤
				}
			}
			getchar();// '\n'
		}

		// 初始化
		memset(column, FALSE, sizeof(column));
		solution = 0;

		backTrack(k, 0);// 回溯

		printf("%d\n", solution);
	}
	return 0;
}

提交結果

在這裏插入圖片描述

相關文章
相關標籤/搜索