1. 程式人生 > >牛客網編程練習之編程馬拉松:紅與黑

牛客網編程練習之編程馬拉松:紅與黑

簡單 rgs int 並且 ner http smart == https

題目描述

有一間長方形的房子,地上鋪了紅色、黑色兩種顏色的正方形瓷磚。你站在其中一塊黑色的瓷磚上,只能向相鄰的(上下左右四個方向)黑色瓷磚移動。請寫一個程序,計算你總共能夠到達多少塊黑色的瓷磚。

輸入描述:

輸入包含多組數據。

每組數據第一行是兩個整數 m 和 n(1≤m, n≤20)。緊接著 m 行,每行包括 n 個字符。每個字符表示一塊瓷磚的顏色,規則如下:

1. “.”:黑色的瓷磚;
2. “#”:白色的瓷磚;
3. “@”:黑色的瓷磚,並且你站在這塊瓷磚上。該字符在每個數據集合中唯一出現一次。

輸出描述:

對應每組數據,輸出總共能夠到達多少塊黑色的瓷磚。

示例1

輸入

9 6
....#.
.....#
......
......
......
......
......
#@...#
.#..#.

輸出

45

采用簡單的遍歷、標記即可。

AC代碼:

import java.util.Scanner;

/**
 * @author CC11001100
 */
public class Main {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		while(sc.hasNextLine()){
			int n = sc.nextInt();
			int m = sc.nextInt();
			sc.nextLine();

			char[][] map = new char[n][m];
			for(int i=0; i<n; i++){
				map[i] = sc.nextLine().toCharArray();
			}

			System.out.println(resolve(map));
		}
	}

	private static int resolve(char[][] map){

		int startX = -1;
		int startY = -1;

		loop: for(int i=0; i<map.length; i++){
			for(int j=0; j<map[i].length; j++){
				if(map[i][j]==‘@‘){
					startX = i;
					startY = j;
					break loop;
				}
			}
		}

		map[startX][startY] = ‘o‘;
		dfs(map, startX, startY);

		int res = 0;
		for(int i=0; i<map.length; i++){
			for(int j=0; j<map[i].length; j++){
				if(map[i][j]==‘o‘){
					res++;
				}
			}
		}

		return res;
	}

	private static final Integer[][] next = new Integer[][] {
			{0, -1},
			{1, 0},
			{0, 1},
			{-1, 0}
	};

	private static void dfs(char[][] map, int x, int y){

		for(int i=0; i<next.length; i++){
			int nextX = x + next[i][0];
			int nextY = y + next[i][1];

			if(nextX<0 || nextX>=map.length || nextY<0 || nextY>=map[x].length){
				continue;
			}

			if(map[nextX][nextY] == ‘#‘ || map[nextX][nextY]==‘o‘){
				continue;
			}

			map[nextX][nextY] = ‘o‘;
			dfs(map, nextX, nextY);
		}

	}

}

題目來源: https://www.nowcoder.com/practice/5017fd2fc5c84f78bbaed4777996213a?tpId=3&tqId=10879&tPage=1&rp=&ru=/ta/hackathon&qru=/ta/hackathon/question-ranking

牛客網編程練習之編程馬拉松:紅與黑