close

題目取自於ITSA協作平台
題目:糖果分享

 

問題描述 :

兒童節前夕,老師把全班同學的座位排成格子狀,並且準備了一袋一袋的糖果要分給小朋友們。老師把一袋一袋的糖果放在某幾個同學的抽屜裡,拿到一袋糖果的同學必須而且只能把糖果分給他前後左右的同學。請寫一個程式幫老師檢查看看,是不是全班的同學都可以拿到糖果呢?

 

輸入說明 :

輸入檔中第一行為一個正整數N,代表共有幾組測試資料。之後接下來每筆資料的第一行為兩個數字n、m和L, 1 ≤ n ≤ 20, 1 ≤ m ≤ 20, 1 ≤ L ≤ 100,以空格隔開,表示座位共有n行、m列以及糖果共有L袋,第二行開始每行有2個數字x和y,以一個空格隔開,共有L行,每一組x、y代表糖果放在第x行、第y列的抽屜裡。

輸出說明 :

若全部的同學都可以拿到糖果,則輸出Y,否則輸出N。每筆測試資料輸出於一行。

範例 :

Sample Input:

Sample Output:

3
2 3 1
1 1
4 3 4
1 2
2 2
3 2
4 2
5 4 5
1 3
2 1
3 4
4 1
5 3

N
Y
N

 

Code:

  1. import java.util.Scanner;  
  2. public class Main{        
  3.     public static void main(String[] args){        
  4.         Scanner sc=new Scanner(System.in);     
  5.         int a = sc.nextInt();  
  6.         for(int b=0;b<a;b++){  
  7.         int n = sc.nextInt();     
  8.         int m = sc.nextInt();     
  9.         int l = sc.nextInt();   
  10.         int[][] arr = new int[n+2][m+2];  
  11.         for(int c=0;c<l;c++){  
  12.             int x = sc.nextInt();  
  13.             int y = sc.nextInt();  
  14.             arr[x][y]=1;  
  15.             arr[x+1][y]=1;  
  16.             arr[x-1][y]=1;  
  17.             arr[x][y+1]=1;  
  18.             arr[x][y-1]=1;  
  19.         }  
  20.         int num=0;  
  21.         for(int c=1;c<n+1;c++){  
  22.             for(int d=1;d<m+1;d++){  
  23.                 if(arr[c][d]==0){  
  24.                     num++;  
  25.                     break;  
  26.                 }  
  27.             }  
  28.         }  
  29.         if(num==0)  
  30.             System.out.println("Y");  
  31.         else  
  32.             System.out.println("N");  
  33.         }  
  34.     }  
  35. }  
arrow
arrow
    文章標籤
    JAVA ITSA 糖果分享
    全站熱搜

    ニャー提督 發表在 痞客邦 留言(1) 人氣()