[Java] POJ 1321

一、思路

  • 和N皇后有点像,不过比它简单,只需要考虑不在同一行和列
  • 用col[] 数组记录,某列是否有棋子。 col[i] 代表第i列放了一个棋子
  • dfs分2个方向。 因为题目给定放K个棋子,说明有些行可以不放棋子
    1.一个方向是该行要放棋子
    //1.在该行放棋子
      	for (int i = 0; i < n; i++) {
      		if (!col[i] && G[row][i] == '#') {
      			col[i] = true;
      			dfs(row + 1, cnt + 1);
      			//回溯
      			col[i] = false;
      		}
      	}
    
    2.一个方向是该行不放棋子
    	//2.不在该行放棋子
      	dfs(row + 1, cnt);
    

二、代码

import java.util.*;

public class POJ_1321 {
	static int n, k, ans;
	static char[][] G = new char[10][10];
	static boolean[] col = new boolean[10]; //代表某列是否放了棋子 true为放了棋子
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while ((n = sc.nextInt()) != -1 && (k = sc.nextInt()) != -1) {
			for (int i = 0; i < n; i++) {
				char[] str = sc.next().toCharArray();
				for (int j = 0; j < n; j++) {
					G[i][j] = str[j];
				}
			}
			ans = 0;
			dfs(0,0);
			System.out.println(ans);
		}
	}
	static void dfs(int row, int cnt) {
		if (cnt == k) {
			ans++;
			return;
		}
		if (row > n) return;
		
		//1.在该行放棋子
		for (int i = 0; i < n; i++) {
			if (!col[i] && G[row][i] == '#') {
				col[i] = true;
				dfs(row + 1, cnt + 1);
				//回溯
				col[i] = false;
			}
		}
		//2.不在该行放棋子
		dfs(row + 1, cnt);
	}
}

你可能感兴趣的:(算法)