首页 > 代码库 > java实现——003二维数组中的查找

java实现——003二维数组中的查找

 1 import java.util.Scanner;
 2 
 3 public class T003 {
 4 
 5     public static void main(String[] args) {
 6         Scanner in = new Scanner(System.in);
 7         int rows = 0, cols = 0;
 8         rows = in.nextInt();
 9         cols = in.nextInt();
10         int a[][] = new int[rows][cols];
11         for (int i = 0; i < rows; i++) {
12             for (int j = 0; j < cols; j++) {
13                 a[i][j] = in.nextInt();
14             }
15         }
16         System.out.println(find(a, rows, cols, 7));
17     }
18 
19     public static boolean find(int a[][], int rows, int cols, int f) {
20         boolean found = false;
21         int row = 0;
22         int col = cols - 1;
23         while (row < rows && col >= 0) {
24             if (a[row][col] == f) {
25                 found = true;
26                 break;
27             } else if (a[row][col] > f) {
28                 --col;
29             } else {
30                 ++row;
31             }
32         }
33         return found;
34     }
35 }