uva 639 - Don't Get Rooked

回溯法,注意回溯回来之后状态要恢复,冲突判断是从当前点向四周辐射,直到出界或者遇到墙,如果有遇到其他车,说明冲突。

 

#include<stdio.h>

int n;
int board[5][5];
int maxNum;

int isConflicted(int i, int j) {
	int o, p;
	for (o = i; o >= 0 && board[o][j] != 0; o--) {
		if (board[o][j] == -1)
			return 1;
	}
	for (o = i; o < n && board[o][j] != 0; o++) {
		if (board[o][j] == -1)
			return 1;
	}

	for (p = j; p >= 0 && board[i][p] != 0; p--) {
		if (board[i][p] == -1)
			return 1;
	}
	for (p = j; p < n && board[i][p] != 0; p++) {
		if (board[i][p] == -1)
			return 1;
	}

	return 0;
}

void dfs(int num) {
	int i, j;
	for (i = 0; i < n; i++)
		for (j = 0; j < n; j++) {
			if (board[i][j] == 1 && !isConflicted(i, j)) {
				board[i][j] = -1;
				dfs(num + 1);
				board[i][j] = 1;

			}
		}
	if (num > maxNum)
		maxNum = num;

}

int main() {
	while (scanf("%d", &n)) {
		if (n == 0)
			break;
		maxNum = 0;
		int i, j;
		char ch;
		getchar();
		for (i = 0; i < n; i++) {
			for (j = 0; j < n; j++) {
				scanf("%c", &ch);
				if (ch == '.')
					board[i][j] = 1;
				else if (ch == 'X')
					board[i][j] = 0;
				else {
					printf("error!");
				}
			}
			getchar();
		}

		dfs(0);
		printf("%d\n", maxNum);

	}

	return 0;
}

 

你可能感兴趣的:(get)