版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qq_29110265/article/details/84139927
问 题 描述: |
问题描述 消除类游戏是深受大众欢迎的一种游戏,游戏在一个包含有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;
}
}