今日头条笔试第一题,求解输入输出?
请问我输入输出哪里有毛病呀?
package com.sonihr.NowCoderExam;/*
@author 黄大宁Rhinos
@date 2019/4/14 - 10:10
**/
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Scanner;
public class ZiJieTiaoDong4_14Test1 {
public static int change4Dir(int i,int j,int rows,int cols,int[][] matrix){
if(i<0||i>=rows||j<0||j>=cols){
return 0;
}
if(matrix[i][j]==1){
matrix[i][j] = -1;
return 1;
}
return 0;
}
public static int changeToProgrammer(int rows,int cols,int[][] matrix){
int time = 0;
int oneCnt = 0;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(matrix[i][j]==1)
oneCnt++;
}
}
int preOneCnt = 0;
while(oneCnt!=0&&oneCnt!=preOneCnt){
time++;
preOneCnt=oneCnt;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(matrix[i][j]==2){
int changeCnt =
change4Dir(i+1,j,rows,cols,matrix)+
change4Dir(i-1,j,rows,cols,matrix)+
change4Dir(i,j+1,rows,cols,matrix)+
change4Dir(i,j-1,rows,cols,matrix);
oneCnt -= changeCnt;
}
}
}
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(matrix[i][j]==-1)
matrix[i][j]=2;
}
}
}
if(oneCnt==0)
return time;
else
return -1;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
while(in.hasNextLine()){
String line = in.nextLine();
if(!line.equals(""))
list.add(line);
else{
int rows = list.size();
int cols = list.get(0).split(" ").length;
int[][] matrix = new int[rows][cols];
for(int i=0;i<rows;i++){
String[] str = list.get(i).split(" ");
for(int j=0;j<cols;j++){
matrix[i][j]= Integer.valueOf(str[j]);
}
}
System.out.println(changeToProgrammer(rows,cols,matrix));
list.clear();
}
}
}
}
/*
1 2 1
1 1 0
0 1 1
1 2
2 1
1 2
0 1
0 1
1 1
*/
#笔试题目##春招##Java#