思路:可以用DFS求解。遍历这个二维数组,没发现一次未被发现的‘@’,便将其作为起点进行搜索。最后的答案,是这个遍历过程中发现了几次为被发现的‘@’
import java.util.*;public class Main{ public static void main(String[] args) { Scanner in = new Scanner( System.in ); while( true ) { int rows, cols; rows = in.nextInt(); // read the rows cols = in.nextInt(); // read the cols if( rows == 0 && cols == 0 ) { // the input end break; } OilDeposits od = new OilDeposits( rows, cols ); od.readGrids( in ); // read the strings System.out.println( od.getPocketsAmount() ); } }}class OilDeposits{ private int rows, cols; private char grids[][]; private boolean vis[][]; private final int dir[][] = { // the eight directions {-1,-1}, {-1,0}, {-1,1}, {0,-1}, {0,1}, {1,-1}, {1,0}, {1,1} }; private final char EMPTY = '*'; private final char EXIST = '@'; public OilDeposits( int rows, int cols ) { this.rows = rows; this.cols = cols; this.grids = new char[ rows + 5 ][ cols + 5 ]; this.vis = new boolean[ rows ][ cols ]; for( int i=0; i= this.rows || col < 0 || col >= this.cols || vis[row][col] || this.grids[row][col] == EMPTY ) { return false; } return true; } public void readGrids( Scanner in ) { String str; for( int i=0; i
其中之所以将Scanner的对象进行传递,是因为如果重新声明一个Scanner的对象,会使输入出错,错误的具体表现为一直等待输入,尽管已经在Console中输入了数据。猜测可能是未关闭上一个Scanner的对象导致的,所以这里将Scanner的对象进行传递。