第四范式AC代码
受到一个月碾压之后自己终于也通关一次,激动。
第一题是leetcode原题,第二题DFS。
import java.util.Scanner; public class Main { public static boolean searchMatrix(int[][] matrix, int target) { if (matrix.length == 0) return false; int i = 0, j = matrix[0].length - 1; while (i <= matrix.length - 1 && j >= 0) { if (matrix[i][j] == target) return true; else if (matrix[i][j] > target) j--; else if (matrix[i][j] < target) i++; } return false; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int m = sc.nextInt(); int n = sc.nextInt(); int[][] matrix = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int tmp = sc.nextInt(); matrix[i][j] = tmp; } } int target = sc.nextInt(); System.out.println(searchMatrix(matrix, target)); } }
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { static boolean flag = true; public static int searchZero(int[] paint) { for (int i = 0; i < paint.length; i++) { if (paint[i] == 0) return i; } return -1; } // 0 未染色 1 白 2 黑 public static void search(List<Integer>[] graph, int curNode, int[] paint, int color) { int antiColor = color == 1 ? 2 : 1; paint[curNode] = color; List<Integer> neibour = graph[curNode]; for (int i = 0; i < neibour.size(); i++) { if (paint[neibour.get(i)] == color) { flag = false; return; } } for (int i = 0; i < neibour.size(); i++) { if (paint[neibour.get(i)] == 0) { search(graph, neibour.get(i), paint, antiColor); } if (flag == false) break; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); List<Integer>[] graph = new List[n]; for (int i = 0; i < n; i++) { graph[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; graph[a].add(b); graph[b].add(a); } int[] paint = new int[n]; int idx = searchZero(paint); while (idx != -1) { search(graph, idx, paint, 1); if (flag == false) { System.out.println("No"); break; } idx = searchZero(paint); } if (flag) System.out.println("Yes"); } }
#第四范式##笔试题目#