# Search consecutive number.

I have a problem about searching consecutive four equal numbers in 2-D array. How could I find each of horizontal,vertical,oblique line have the same number and return true or false ? int[][] array2 = {

{0,1,2,1,1,6,1},

{0,1,6,8,6,0,1},

{5,4,2,1,8,2,9},

{6,5,4,1,1,9,1},

{1,3,6,4,4,0,7},

{3,4,3,3,4,0,7}};

For instance, in array2, array2, array2, array2, array2 have value 4, so that program will return true.

### 1 個解答

• 最佳解答

"horizontal, vertical, and oblique" comprises the surround 8 numbers (not only 4), where applicable. It means to check array[i][j], the code has to go through the numbers where i = i-1, i, i+1, and j = j-1, j, j+1.

2012-03-16 12:31:59 補充：

請參考我的做法

public class Y1590 {

public static void main(String[] args) {

int[][] array2 = {

{0,1,2,1,1,6,1},

{0,1,6,8,6,0,1},

{5,4,2,1,8,2,9},

{6,5,4,1,1,9,1},

{1,3,6,4,4,0,7},

{3,4,3,3,4,0,7}};

boolean b = searchForEqual(array2);

System.out.println(b);

}

public static boolean searchForEqual(int[][] ary) {

boolean hasEqual = false;

for (int i = 0; i < ary.length; i++) {

for (int j = 0; j < ary[i].length; j++) {

int x = ary[i][j];

if (i-1 >= 0) { // search previous row

if (j-1 >= 0 && ary[i-1][j-1] == x) {

hasEqual = true;

print(i, j, i-1, j-1, x);

}

if (j+1 < ary[i].length && ary[i-1][j+1] == x) {

hasEqual = true;

print(i, j, i-1, j+1, x);

}

if (ary[i-1][j] == x) print(i, j, i-1, j, x);

}

if (i+1 < ary.length) { // search later row

if (j-1 >= 0 && ary[i+1][j-1] == x) {

hasEqual = true;

print(i, j, i+1, j-1, x);

}

if (j+1 < ary[i].length && ary[i+1][j+1] == x) {

hasEqual = true;

print(i, j, i+1, j+1, x);

}

if (ary[i+1][j] == x) print(i, j, i+1, j, x);

}

// search current row

if (j-1 >= 0 && ary[i][j-1] == x) {

hasEqual = true;

print(i, j, i, j-1, x);

}

if (j+1 < ary[i].length && ary[i][j+1] == x) {

hasEqual = true;

print(i, j, i, j+1, x);

}

}

}

return hasEqual;

}

public static void print(int i, int j, int m, int n, int x) {

System.out.println("array[" + i + "][" + j + "] = array[" + m +

"][" + n + "] = " + x);

}

}