判断二维矩阵中是否存在连续四个相同的数

Java 实验课:2013/10/24 

           输入二维矩阵的行和列(row>5,col>5),然后用[0,9]的随机数填充矩阵,检测矩阵中四个方向( 水平,竖直,左斜,右斜)是否存在连续四个相同的数

package sunquan;

import java.util.*;

class rectangle {
	private int row, col;
	int[][] rec;

	rectangle() {//构造函数:是没有返回值
	}

	rectangle(int n, int m) {
		row = n;col = m;
		rec = new int[row][col];
	}

	public void show() {
		for (int i = 0; i < row; i++) {
			for (int j = 0; j < col; j++) {
				System.out.print(rec[i][j] + " ");
			}
			System.out.println();
		}
	}
}



public class Test {
	private static int n, m;
	private  static rectangle r ;

	public  Boolean solve() {
		for (int i = 0; i < n ; i++)
			for (int j = 0; j < m ; j++) {
				int f=BFS( i, j);
				if (f>0) {
					switch(f){
					case 1:  System.out.println("竖直向下"); break;
					case 2:  System.out.println("水平向右"); break;
					case 3:  System.out.println("右斜方"); break;
					case 4:  System.out.println("左斜方"); break;
					}
					System.out.println("第"+(i+1)+"行,"+"第"+(j+1)+"列");
					return true;
				}
			}
		return false;
	}

	public  int BFS( int a, int b) {
		int i;
		for (i = 0; i <  3 && a+i+1=0; i++)
			if (r.rec[a+i][b-i] != r.rec[a+i+1][b-i-1]) {
				break;
			}
		if (i == 3) return 4;

		return 0;
	}

	public static void main(String[] args) {

		Scanner in = new Scanner(System.in);
		do {
			System.out.println("请输入行和列(>5)");
			n = in.nextInt();
			m = in.nextInt();
			if (n < 5 || m < 5)
				System.out.println("输入不合法!");
			else
				break;
		} while (true);
		
		r = new rectangle(n, m);
		Test t=new Test();
		Random ran = new Random();
		// 随机生成
		for (int i = 0; i < n; i++)
			for (int j = 0; j < m; j++) {
				r.rec[i][j] = ran.nextInt(10);
			}
		r.show();
		if (t.solve()==false) System.out.println("不存在有连续四个相同的数!");
		
		in.close();

	}

}



你可能感兴趣的:(Java学习笔记-大三)