第一题
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main2 { public static int solution(char[][] matrix){ if (matrix == null || matrix.length<1 || matrix[0].length<1) return 0; int m = matrix.length, n = matrix[0].length; int ans = 0; for (int l = 0;l<m;l++){ for (int r = 0;r<n;r++){ if (matrix[l][r] == 'S'){ ans++; search(matrix,l,r); } } } return ans; } private static void search(char[][] matrix,int l,int r){ int m = matrix.length , n = matrix[0].length; if (l>=m || r>=n || l<0 || r<0 || matrix[l][r] == 'H') return; matrix[l][r] = 'H'; search(matrix,l-1,r); search(matrix,l+1,r); search(matrix,l,r-1); search(matrix,l,r+1); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); String m_n = sc.next(); String[] strings = m_n.split(","); int m = Integer.parseInt(strings[0]) , n = Integer.parseInt(strings[1]); List<String> stringList = new ArrayList<>(); for (int i = 0;i<m;i++){ stringList.add(sc.next()); } char[][] matrix = new char[m][n]; for (int i = 0;i<m;i++){ for (int j = 0;j<n;j++){ matrix[i][j] = stringList.get(i).charAt(j); } } int ans = solution(matrix); System.out.println(ans); } }
全部评论
(0) 回帖