การตรวจสอบเงื่อนไขในเมทริกซ์ 2 มิติ
โจทย์
You are given a 2D matrix grid of size . You need to check if each cell is:
- Equal to the cell below it, i.e. == (if it exists).
- Different from the cell to its right, i.e. != (if it exists).
Return true if all the cells satisfy these conditions, otherwise, return false.
Input:
- Row and Col sizes
- Input array
Output:
- True if conditions are met, false otherwise
| Input | Output |
|---|---|
| 2 3 1 0 2 1 0 2 | true |
| 2 3 1 1 1 0 0 0 | false |
โค้ด
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = scanner.nextInt();
}
}
boolean isValid = true;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] != matrix[i + 1][j]) {
isValid = false;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m - 1; j++) {
if (matrix[i][j] == matrix[i][j + 1]) {
isValid = false;
}
}
}
System.out.println(isValid);
}
}คำอธิบาย
1. การประกาศคลาสและรับขนาดเมทริกซ์
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // จำนวนแถว
int m = scanner.nextInt(); // จำนวนคอลัมน์2. การสร้างและรับข้อมูลเมทริกซ์
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = scanner.nextInt();
}
}3. การตรวจสอบเงื่อนไข
boolean isValid = true; // ตั้งค่าเริ่มต้นเป็น true
// ตรวจสอบเงื่อนไขที่ 1: เปรียบเทียบกับเซลล์ด้านล่าง
for (int i = 0; i < n - 1; i++) { // วนถึงแถวรองสุดท้าย
for (int j = 0; j < m; j++) {
if (matrix[i][j] != matrix[i + 1][j]) { // เปรียบเทียบกับแถวถัดไป
isValid = false;
}
}
}
// ตรวจสอบเงื่อนไขที่ 2: เปรียบเทียบกับเซลล์ด้านขวา
for (int i = 0; i < n; i++) {
for (int j = 0; j < m - 1; j++) { // วนถึงคอลัมน์รองสุดท้าย
if (matrix[i][j] == matrix[i][j + 1]) { // เปรียบเทียบกับคอลัมน์ถัดไป
isValid = false;
}
}
}4. การแสดงผล
System.out.println(isValid);แผนภาพการทำงาน
การเปรียบเทียบเซลล์
เงื่อนไขที่ 1: เปรียบเทียบกับเซลล์ด้านล่าง
[i,j] ต้องเท่ากับ→ [i+1,j]
1 1
1 1เงื่อนไขที่ 2: เปรียบเทียบกับเซลล์ด้านขวา
[i,j] ต้องต่างจาก→ [i,j+1]
1 2ตัวอย่างการทำงาน
ตัวอย่างที่ 1: เมทริกซ์ที่ถูกต้อง
Input:
3 3
1 2 3
1 2 3
1 2 3
การตรวจสอบ:
เงื่อนไขที่ 1: ✓
- [0,0]=1 == [1,0]=1
- [0,1]=2 == [1,1]=2
- [0,2]=3 == [1,2]=3
- [1,0]=1 == [2,0]=1
- [1,1]=2 == [2,1]=2
- [1,2]=3 == [2,2]=3
เงื่อนไขที่ 2: ✓
- [0,0]=1 != [0,1]=2
- [0,1]=2 != [0,2]=3
- [1,0]=1 != [1,1]=2
- [1,1]=2 != [1,2]=3
- [2,0]=1 != [2,1]=2
- [2,1]=2 != [2,2]=3
Output: trueตัวอย่างที่ 2: เมทริกซ์ที่ไม่ถูกต้อง
Input:
2 2
1 1
2 2
การตรวจสอบ:
เงื่อนไขที่ 1: ✗
- [0,0]=1 != [1,0]=2
- [0,1]=1 != [1,1]=2
เงื่อนไขที่ 2: ✗
- [0,0]=1 == [0,1]=1
- [1,0]=2 == [1,1]=2
Output: falseปรับปรุงล่าสุด