我从左下方和行进在顺时针方向开始直到没有字符被保留。这是我的代码。我有字符的2D矩阵,以及具有麻烦搜索矩阵螺旋
import java.io.*;
import java.util.*;
public class Solution {
static int count = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
char[][] matrix = new char[n][m];
char[] temp = new char[n*m];
for(int r=0;r<n;r++){
for(int col=0;col<m;col++){
matrix[r][col] = sc.next().charAt(col);
}
}
int k=0, l = 0;
while(k < n && l < m){
if(l<m){
for(int i = n-1;i>=k;i--){
temp[count] = matrix[i][l];
count++;
}
l++;
}
for(int i = l;i<m;i++){
temp[count] = matrix[k][i];
count++;
}
k++;
for(int i = k;i<n;i++){
temp[count] = matrix[i][m-1];
count++;
}
m--;
if(k < n){
for(int i = m-1;i>=l;i--){
temp[count] = matrix[n-1][i];
}
n--;
}
}
String code = String.valueOf(temp);
String[] dec = code.split("#");
//System.out.println(dec);
int count2 = dec.length;
System.out.println(count2);
}
}
所以任何人都可以指出我要去哪里错了吗?我从左下角开始,爬上去,向右走,然后下去,向左走,继续,直到没有元素离开。
下螺旋状的一部分吗? –
你可以通过循环头文件for(int i = m-1; i> = l; i - )'在源代码中找到它。 ' – kgeorgiy
狗屎错过了,感谢指出一个出 –