Skip to Content
CoursesCSC122โปรแกรมจำลองการคลิกตาราง

โปรแกรมจำลองการคลิกตาราง

โจทย์

Giving a grid (two-dimensional array) containing numbers, write a program to change the number by 1 per click to the clicked cell and its adjacent cells (i.e., right cell, left cell, top cell, bottom cell). The number will be changed up to 3. If the cell already contains value of 3, the number will be changed back to 1 again. For example, giving the array of 4 rows and 5 columns, if the clicked position is at (1,2) (2,2), (1,3) and (1,3) respectively, the result is shown as below.

Do Or Die Exam

The input has three parts. The first part is two numbers indicate row and column and the arrays. The second part is a number indicate number of clicks. The last part is the list of clicked position in a pair of row and column.

InputOutput
4 5
4
1 2
2 2
1 3
1 3
0 0 1 2 0
0 1 1 3 2
0 1 2 3 0
0 0 1 0 0

โค้ด

import java.util.*; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int rows = scanner.nextInt(); int cols = scanner.nextInt(); int[][] grid = new int[rows][cols]; int clicks = scanner.nextInt(); for (int i = 0; i < clicks; i++) { int rowPos = scanner.nextInt(); int colPos = scanner.nextInt(); click(grid, rowPos - 1, colPos); //Top click(grid, rowPos, colPos - 1); //Left click(grid, rowPos, colPos); //Center click(grid, rowPos, colPos + 1); //Right click(grid, rowPos + 1, colPos); //Bottom } for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { System.out.print(grid[i][j] + " "); } System.out.println(); } } private static void click(int[][] grid, int row, int col) { try { if (grid[row][col] == 3) { grid[row][col] = 1; } else { grid[row][col]++; } } catch (Exception ignored) { } } }

คำอธิบาย

ปรับปรุงล่าสุด