Problem description
Elimination is a popular game. The game is played on a chessboard with n rows and m columns. Each row and column of the chessboard has a colored chessboard on the square. When there are three or more chessboards of the same color in a row or column, these chessboards are eliminated. When there are many places that can be eliminated, the chess pieces in these places will be eliminated at the same time.
Now give you a chessboard with n rows and m rows. Each square in the chessboard has a chessboard. Please give a chessboard that has been eliminated once.
Note: A chess piece may be eliminated at the same time in a row and a column.
Input format
The first line of input contains two integers n and m, separated by spaces, representing the number of rows and columns on the chessboard, respectively.
Next, n rows, m integers per row, separated by spaces, represent the color of the pieces in each square. Colors are numbered 1 to 9.
Output format
Output n rows, m integers per row, adjacent integers are separated by a space, indicating the chessboard after one elimination. If the chess pieces in a square are eliminated, the corresponding square outputs 0, otherwise the color number of the chess pieces is output.

import java.util.*;
public class Main {

	public static void main(String[] args) {
		// Method stub for TODO automatic generation
		Scanner in=new Scanner(System.in);
		int n=in.nextInt();
		int m=in.nextInt();
		int[][] chessBoard=new int[n][m];
		boolean[][] result=new boolean[n][m];
		for(int i=0;i<n;i++) {
			for(int j=0;j<m;j++) {
				chessBoard[i][j]=in.nextInt();
			}
		}
		int begin=0;
		int end=0;
		for(int i=0;i<n;i++) {//Lateral elimination
			begin=0;
			end=0;
			for(int j=1;j<m;j++) {
				if(chessBoard[i][j]==chessBoard[i][j-1]) {
					end=j;
				}else {
					if(end-begin+1>=3) {//eliminate
						for(int k=begin;k<=end;k++) {
							result[i][k]=true;
						}
						begin=j;
						end=j;
					}else {//Update pointer
						begin=j;
						end=j;
					}
				}
			}
			if(end==m-1&&(end-begin+1)>=3) {//eliminate
				for(int k=begin;k<=end;k++) {
					result[i][k]=true;
				}
			}
		}
		for(int i=0;i<m;i++) {
			begin=0;
			end=0;
			for(int j=1;j<n;j++) {
				if(chessBoard[j][i]==chessBoard[j-1][i]) {
					end=j;
				}else {
					if(end-begin+1>=3) {//eliminate
						for(int k=begin;k<=end;k++) {
							result[k][i]=true;
						}
						begin=j;
						end=j;
					}else {//Update pointer
						begin=j;
						end=j;
					}
				}
			}
			if(end==n-1&&(end-begin+1)>=3) {//eliminate
				for(int k=begin;k<=end;k++) {
					result[k][i]=true;
				}
			}
		}
		for(int i=0;i<n;i++) {
			for(int j=0;j<m;j++) {
				if(!result[i][j]) {
					System.out.print(chessBoard[i][j]+" ");
				}else {
					System.out.print(0+" ");
				}	
			}
			System.out.println();
		}
         in.close();
         
	}

}