問 題 描述: |
問題描述 消除類遊戲是深受大衆歡迎的一種遊戲,遊戲在一個包含有n行m列的遊戲棋盤上進行,棋盤的每一行每一列的方格上放着一個有顏色的棋子,當一行或一列上有連續三個或更多的相同顏色的棋子時,這些棋子都被消除。當有多處可以被消除時,這些地方的棋子將同時被消除。 輸入格式 輸入的第一行包含兩個整數n, m,用空格分隔,分別表示棋盤的行數和列數。 輸出格式 輸出n行,每行m個整數,相鄰的整數之間使用一個空格分隔,表示經過一次消除後的棋盤。如果一個方格中的棋子被消除,則對應的方格輸出0,否則輸出棋子的顏色編號。 樣例輸入 4 5 樣例輸出 2 2 3 0 2 樣例說明 棋盤中第4列的1和第4行的2可以被消除,其他的方格中的棋子均保留。 樣例輸入 4 5 樣例輸出 2 2 3 0 2 樣例說明 棋盤中所有的1以及最後一行的3可以被同時消除,其他的方格中的棋子均保留。 評測用例規模與約定 所有的評測用例滿足:1 ≤ n, m ≤ 30。 思想:先通過一行一行遍歷,將需要消除的棋子的座標記錄下來,再通過一列一列遍歷將需要消除的棋子的座標記錄下來。最後遍歷需要消除的棋子的座標,在棋盤上將對應座標置0即可 |
package eliminationGame;
import java.util.HashSet;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();// 行
int m = sc.nextInt();// 列
int comb = 1;// 連續相同顏色棋子記數
int colorPre = 0;// 記錄前一個棋子的顏色
HashSet<Chess> dis = new HashSet<>();// 存儲可消除的棋子
int[][] game = new int[n][m];// 遊戲初始界面
for (int y = 0; y < n; y++)// 佈局同時記錄橫行中可消除的棋子
{
for (int x = 0; x < m; x++) {
game[y][x] = sc.nextInt();
// 若當前棋子與前一個棋子顏色相同,則連續棋子記數+1
if (game[y][x] == colorPre)
{
comb++;
if (x == m - 1 && comb >= 3)// 末尾檢查
{
for (int i = 1; i <= comb; i++) {
Chess chess = new Chess(x - i + 1, y);
dis.add(chess);
}
comb = 1;
}
} else// 若當前棋子與前一個棋子顏色不相同
{
if (comb >= 3)// 當棋子記數達到3或更多時
{
for (int i = 1; i <= comb; i++) {
Chess chess = new Chess(x - i, y);
dis.add(chess);
}
}
colorPre = game[y][x];
comb = 1;// 置1
}
}
comb = 1;// 一行結束置1
colorPre = 0;
}
for (int x = 0; x < m; x++)// 記錄縱行中可消除的棋子
{
for (int y = 0; y < n; y++) {
// 若當前棋子與前一個棋子顏色相同,則連續棋子記數+1
if (game[y][x] == colorPre)
{
comb++;
if (y == n - 1 && comb >= 3)// 末尾檢查
{
for (int i = 1; i <= comb; i++) {
Chess chess = new Chess(x, y - i + 1);
dis.add(chess);
}
comb = 1;
}
} else// 若當前棋子與前一個棋子顏色不相同
{
if (comb >= 3)// 當棋子記數達到3或更多時
{
for (int i = 1; i <= comb; i++) {
Chess chess = new Chess(x, y - i);
dis.add(chess);
}
}
colorPre = game[y][x];
comb = 1;// 置1
}
}
comb = 1;// 一列結束置1
colorPre = 0;
}
for (Chess c : dis)// 消除
{
game[c.y][c.x] = 0;
}
for (int[] a : game) {
for (int b : a)
System.out.print(b + " ");
System.out.println();
}
}
}
class Chess {
int x;
int y;
public Chess(int x, int y) {
this.x = x;
this.y = y;
}
}