在一個給定形狀的棋盤(形狀可能是不規則的)上面擺放棋子,棋子沒有區別,要求擺放時任意的兩個棋子不能放在棋盤中的同一行或者同一列,請編程求解對于給定形狀和大小的棋盤,擺放k個棋子的所有可行的擺放方案C,
Input
輸入含有多組測驗資料,每組資料的第一行是兩個正整數,n k,用一個空格隔開,表示了將在一個n*n的矩陣內描述棋盤,以及擺放棋子的數目, n <= 8 , k <= n
當為-1 -1時表示輸入結束,
隨后的n行描述了棋盤的形狀:每行有n個字符,其中 # 表示棋盤區域, . 表示空白區域(資料保證不出現多余的空白行或者空白列),
Output
對于每一組資料,給出一行輸出,輸出擺放的方案數目C (資料保證C<2^31),Sample Input
2 1 #. .# 4 4 ...# ..#. .#.. #... -1 -1
Sample Output
2 1
注意:
不是每一行都要擺
代碼:
import java.util.Arrays; import java.util.Scanner; public class Main{ static int n,k,cnt; static final int N=10; static char map[][]=new char[N][N]; static boolean vis[]=new boolean[N];//列 static void dfs(int r,int t){//r是行 t是第幾個棋
//這種多個if條件的都要加上return,避免出錯 if(t==k) { cnt++; return; } if(r>=n) return;
//當前行擺放或者不擺放 for(int i=0;i<n;i++){ if(!vis[i] && map[r][i]=='#'){ vis[i]=true; dfs(r+1,t+1); vis[i]=false; } } dfs(r+1,t); } public static void main(String[] args) { Scanner scan=new Scanner(System.in); while(scan.hasNext()){ n=scan.nextInt(); k=scan.nextInt(); if(n==-1 && k==-1) break; for(int i=0;i<n;i++) map[i]=scan.next().toCharArray(); Arrays.fill(vis, false); cnt=0; dfs(0,0); System.out.println(cnt); } } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/98366.html
標籤:其他
