1. 程式人生 > >聯通圖形(去哪兒2017校招真題)

聯通圖形(去哪兒2017校招真題)

題目描述

思路分析

 對於輸入的一行資料, 使用正則表示式將其拆分為字串陣列,對字串陣列中的每個元素進行如下操作:
 給定一個佇列,一個順序表,佇列用於存放當前元素,順序表用於存放其他元素,
 初始化順序表為包含字串陣列中的所有元素,佇列包含字串陣列中的首元素
     當佇列非空時,
        若順序表存在與當前元素聯通的元素,則將該元素放入佇列,並從順序表移除該元素,佇列中的元素作為下一次判斷的當前元素
    當佇列為空時,
        若順序表為空,則輸出"pong"
        否則輸出"pang"

相關API

public static int parseInt(String s, int radix) throws NumberFormatException 方法的作用?

public static int parseInt(String s, int radix) throws NumberFormatException 方法將給定盡職radix的字串s轉換為對應的整數(區分正負)

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
    @SuppressWarnings("resource")
    public static void main(String[] args) {
        Scanner sc = new
Scanner(System.in); // while(sc.hasNext())——輸入一行處理一行 while (sc.hasNext()) { // 接收輸入的一行資料 String str = sc.nextLine(); // 從空白字元處拆分輸入的一行字元並存放於字串陣列strs中 String[] strs = str.split("\\s+"); int n = strs.length; int num[] = new
int[n]; // 佇列——用於存放當前元素 Queue<Integer> q = new LinkedList<Integer>(); // 順序表——存放除當前元素外的其他元素 ArrayList<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { // Integer.parseInt()方法的作用和用法? // 將十六進位制的strs[i]轉換為整數(區分正負) num[i] = Integer.parseInt(strs[i], 16); list.add(num[i]); } // 初始化佇列,包含字串陣列的首元素 q.offer(num[0]); // 初始化順序表,包含字串陣列中除首元素外的其他元素 list.remove(Integer.valueOf(num[0])); // 佇列非空 while (!q.isEmpty()) { // 移除佇列頭元素,並賦值給temp int temp = q.poll(); // 以下為於當前元素聯通的元素 if (list.contains(temp + 1)) { // 插入佇列 q.offer(temp + 1); // 從順序表移除 list.remove(Integer.valueOf(temp + 1)); } if (list.contains(temp - 1)) { q.offer(temp - 1); list.remove(Integer.valueOf(temp - 1)); } if (list.contains(temp + 4)) { q.offer(temp + 4); list.remove(Integer.valueOf(temp + 4)); } if (list.contains(temp - 4)) { q.offer(temp - 4); list.remove(Integer.valueOf(temp - 4)); } } // 佇列為空,若順序表為空則輸出"pong",否則輸出"pang" if (list.isEmpty()) System.out.println("pong"); else System.out.println("pang"); } } }