19 ก.ค. 2554

ปริศนา Matrix จตุรัสกล

ปริศนา Matrix จตุรัสกล

จาก http://www.programming.in.th/task/problem.php?pid=1017

จตุรัสกลเป็นตารางขนาด n x n ที่ระบุจำนวนเต็มมีค่าตั้งแต่ 1 ถึง n2 เอาไว้ตามช่องต่าง ๆ ช่องละหนึ่งจำนวน โดยที่ผลรวมของตัวเลขในแนวนอน แนวตั้ง และแนวทแยงจะได้จำนวนเท่ากันเสมอ ตัวอย่างเช่น



จากนิยามของจตุรัสกลดังกล่าว จงเขียนโปรแกรมเพื่อตรวจสอบว่าตารางที่ให้มาเป็นจตุรัสกลหรือไม่

หมายเหตุ: จตุรัสกลที่กล่าวถึงในโจทย์ข้อนี้ จะหมายถึง จตุรัสกลทั่วไป (Normal magic square) ซึ่งจำนวนในแต่ละช่องจะต้องไม่ีซ้ำกัน

ข้อมูลนำเข้า
บรรทัดแรก
เป็นจำนวนเต็ม n (1 <= n <= 10) ใช้กำหนดขนาดของตาราง
บรรทัดที่ 2 ถึง n+1 แต่ละบรรทัดเป็นจำนวนเต็ม n จำนวนซึ่งคั่นด้วยช่องว่างหนึ่งช่อง โดยแต่ละค่ามีค่าอยู่ระหว่าง 1 ถึง n2

ข้อมูลส่งออก
บรรทัดแรก
พิมพ์คำว่า “Yes” ถ้าหากตารางที่ให้มาเป็นจตุรัสกล ไม่เช่นนั้นให้พิมพ์คำว่า “No” โดยไม่มีเครื่องหมายคำพูด

ที่มา: การแข่งขันคณิตศาสตร์ วิทยาศาสตร์ โอลิมปิกแห่งประเทศไทย สาขาวิชาคอมพิวเตอร์ ประจำปี 2547
ตัวอย่างข้อมูลนำเข้า  ตัวอย่างข้อมูลส่งออก
4
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
Yes

ความช่วยเหลือ: ไม่มีคำใบ้สำหรับปัญหานี้
สำหรับ input ผมได้ทำเป็น ไฟล์ txt ชื่อ input.txt

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class Matrix {
 private ArrayList<String> listinput = new ArrayList<String>();
 private HashMap<Integer, Integer> mapnum = new HashMap<Integer, Integer>();
 int[][] matrix;
 private int size = 0;
 public Matrix(){
  FiletoString("input.txt");
  matrix = new int[size][size];
  System.out.println(size);
  int row = 0;
  for (String str : listinput) {
   String[] allnum = str.split(" ");
   for (int i = 0; i < allnum.length; i++) {
    matrix[row][i] = Integer.parseInt(allnum[i]);
    System.out.print(matrix[row][i]+" ");
   }
   System.out.println();
   row++;
  }
  for(int round = 0;round<2;round++){
   int sum = 0;
   for (int i=0;i<size;i++) {
    if(round==0)
     sum+=matrix[i][i];
    else{
     sum+=matrix[i][size-(i+1)];
    }
   }
   System.out.println(">>"+sum);
   mapnum.put(sum,0);
   for (int i=0;i<matrix.length;i++) {
    sum = 0;
    for (int k=0;k<matrix[i].length;k++) {
     if(round==0)
      sum+=matrix[i][k];
     else
      sum+=matrix[k][i];
    }
    mapnum.put(sum, 0);
    System.out.println(">>"+sum);
   }
  }
  if(mapnum.size()==1)
   System.out.println("Yes");
  else
   System.out.println("No");
 }
 public void FiletoString(String path) {
  try {
   DataInputStream data = new DataInputStream(new FileInputStream(new File(path)));
   int i = 0;
   while(data.available() != 0){
    String read = data.readLine();
    if(i==0)
     size=Integer.parseInt(read);
    else
     listinput.add(read);
    i++;
   }
  } catch (IOException e) {
   System.out.println("File not found "+e.getMessage());
  }
 }
 public static void main(String[] args) {
  new Matrix();
 }
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น