1- 思路
有向图+记录入度数组+出度列表
- 根据输入
- ① 构造遍历构造入度数组
- ② 构造出度列表
- 根据入度数组为 0 的数 加入到 队列中,进行处理
2- 实现
⭐207. 课程表——题解思路
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
int[] inNums = new int[numCourses];
List<List<Integer>> outList = new ArrayList<>();
Queue<Integer> queue = new LinkedList<>();
for(int i = 0 ; i < numCourses ;i++){
outList.add(new ArrayList<>());
}
for(int[] num:prerequisites){
inNums[num[0]]++;
outList.get(num[1]).add(num[0]);
}
for(int i = 0 ; i < numCourses;i++){
if(inNums[i] == 0){
queue.add(i);
}
}
while(!queue.isEmpty()){
int pre = queue.poll();
numCourses--;
for(int num: outList.get(pre)){
inNums[num]--;
if(inNums[num]==0){
queue.add(num);
}
}
}
return numCourses==0;
}
}
3- ACM 实现
public class canFinish {
public static boolean canFinish(int numCourses, int[][] prerequisites){
int[] inNums = new int[numCourses];
List<List<Integer>> outList = new ArrayList<>();
Queue<Integer> queue = new LinkedList<>();
for(int i = 0 ; i < numCourses;i++){
outList.add(new ArrayList<>());
}
for(int[] num:prerequisites){
inNums[num[0]] ++;
outList.get(num[1]).add(num[0]);
}
for(int i = 0 ; i < numCourses;i++){
if(inNums[i]==0){
queue.add(i);
}
}
while(!queue.isEmpty()){
int pre = queue.poll();
numCourses--;
for (int num:outList.get(pre)){
inNums[num]--;
if(inNums[num] == 0){
queue.add(num);
}
}
}
return numCourses==0;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入课程数");
int numCourses = sc.nextInt();
String konge = sc.nextLine();
System.out.println("输入二维数组");
String input = sc.nextLine();
input = input.substring(2,input.length()-2);
String[] rows = input.split("],\\[");
int m = rows.length;
int n = rows[0].split(",").length;
int[][] prerequisites = new int[m][n];
for(int i = 0 ; i < m;i++){
String[] row = rows[i].split(",");
for(int j = 0 ; j < n;j++){
prerequisites[i][j] = Integer.parseInt(row[j]);
}
}
System.out.println("结果是"+canFinish(numCourses,prerequisites));
}
}