小红书笔试第一题求解!!
//调了半个小时只有55% 没记错的话是当时字节笔试的第一题。当时直接AC,搞不懂哪个用例不符合 public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = Integer.parseInt(sc.nextLine());
int[][] arr = new int[N][N];
for (int i = 0; i < N; i++) {
String[] temp = sc.nextLine().split(" ");
N = temp.length;
for (int j = 0; j < N; j++) {
arr[i][j] = Integer.parseInt(temp[j]);
}
}
methodImpl(arr,N);
}
private static void methodImpl(int[][] arr,int N) {
int count = 0;
int[] mark = new int[N];
for (int i = 0; i < N ; i++) {
if(mark[i] == 1) continue;
LinkedList<Integer> temRes = new LinkedList<>();
// temRes.add(i);
mark[i]=1;
for (int j = i+1; j < N; j++) {
if(arr[i][j]==1 && arr[i][j] == arr[j][i]){
temRes.add(j);
mark[j]=1;
}
}
while (!temRes.isEmpty()){
int x = temRes.poll();
for (int j = x+1; j < N ; j++) {
if(arr[x][j] == 1 && arr[x][j] == arr[j][x]){
temRes.add(j);
mark[j] = 1;
}
}
}
count++;
}
System.out.println(count);
}
}
}
#小红书##题解#