โปรแกรม Bomber Man 3D
โจทย์
คุณกำลังสร้างเกม Bomber Man 3D โดยมีสนามขนาด 5x5x5 (เหมือนรูบิคขนาด 5x5x5)
กฎคือ ผู้เล่นสามารถวางระเบิดในเซลล์ใดๆ ของสนามได้ เมื่อระเบิดทำงาน มันจะทำลายทุกเซลล์ไปจนถึงขอบในทั้ง 6 ทิศทาง (คือ บน, ล่าง, ซ้าย, ขวา, หน้า, หลัง)
งานของคุณคือเขียนโปรแกรมเพื่อนับจำนวนเซลล์ที่ถูกทำลายในสนาม เมื่อได้รับจำนวนระเบิดและตำแหน่งของระเบิด
ข้อมูลนำเข้า
- บรรทัดแรกของข้อมูลนำเข้าคือจำนวนระเบิดในสนาม
- บรรทัดต่อ ๆ มาคือตำแหน่งของแต่ละระเบิดในสนาม
ข้อมูลส่งออก
- ผลลัพธ์คือจำนวนรวมของเซลล์ที่ถูกทำลายในสนาม
| Input | Output |
|---|---|
| 2 0 0 0 2 3 4 | 26 |
| 3 1 1 2 0 3 4 2 1 3 | 37 |
โค้ด
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numberOfBombs = scanner.nextInt();
boolean[][][] matrix = new boolean[5][5][5];
for (int i = 0; i < numberOfBombs; i++) {
int x = scanner.nextInt();
int y = scanner.nextInt();
int z = scanner.nextInt();
for (int i1 = 0; i1 < 5; i1++) matrix[i1][y][z] = true;
for (int j1 = 0; j1 < 5; j1++) matrix[x][j1][z] = true;
for (int k1 = 0; k1 < 5; k1++) matrix[x][y][k1] = true;
}
int destroyedCells = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
for (int k = 0; k < 5; k++) {
if (matrix[i][j][k]) destroyedCells++;
}
}
}
System.out.println(destroyedCells);
}
}คำอธิบาย
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numberOfBombs = scanner.nextInt();
boolean[][][] matrix = new boolean[5][5][5];- เราเริ่มด้วยการสร้าง
Scannerเพื่อรับข้อมูลนำเข้า numberOfBombsเก็บจำนวนระเบิดmatrixเป็นอาร์เรย์ 3 มิติขนาด 5x5x5 ที่ใช้เก็บสถานะของแต่ละเซลล์ (true หมายถึงถูกทำลาย)
for (int i = 0; i < numberOfBombs; i++) {
int x = scanner.nextInt();
int y = scanner.nextInt();
int z = scanner.nextInt();
for (int i1 = 0; i1 < 5; i1++) matrix[i1][y][z] = true;
for (int j1 = 0; j1 < 5; j1++) matrix[x][j1][z] = true;
for (int k1 = 0; k1 < 5; k1++) matrix[x][y][k1] = true;
}- ลูปนี้ทำงานตามจำนวนระเบิด
- สำหรับแต่ละระเบิด:
- รับพิกัด x, y, z ของระเบิด
- ทำเครื่องหมายทุกเซลล์ในแนวแกน x เป็น true
- ทำเครื่องหมายทุกเซลล์ในแนวแกน y เป็น true
- ทำเครื่องหมายทุกเซลล์ในแนวแกน z เป็น true
- นี่เป็นการจำลองการระเบิดที่ทำลายทุกเซลล์ในทั้ง 6 ทิศทาง
int destroyedCells = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
for (int k = 0; k < 5; k++) {
if (matrix[i][j][k]) destroyedCells++;
}
}
}- ใช้ลูปซ้อน 3 ชั้นเพื่อนับจำนวนเซลล์ที่ถูกทำลาย (มีค่าเป็น true) ในเมทริกซ์ 3 มิติ
System.out.println(destroyedCells);
}
}- แสดงผลลัพธ์จำนวนเซลล์ที่ถูกทำลาย
หลักการทำงาน
ปรับปรุงล่าสุด