You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于相邻瓦片HashMap判断向量中是否存在相邻瓦片?

问题

给定一个存储瓦片ID的向量,以及定义瓦片相邻关系的映射表adjacents,需要实现逻辑:判断向量中是否存在互为相邻的瓦片,存在则返回true,否则返回false。

示例

  • 输入向量[1 3 19],返回true——因为(adjacents 1)包含3
  • 输入向量[1 14 19],返回false——三个瓦片彼此都不在对方的相邻列表中

相邻关系映射表定义

(def adjacents
  {1 [2 3 4 5 6 7]
   2 [1 3 7 8 9 10]
   3 [1 2 4 10 11 12]
   4 [1 3 5 12 13 14]
   5 [1 4 6 14 15 16]
   6 [1 5 7 16 17 18]
   7 [1 2 6 8 18 19]
   8 [2 7 8 18]
   9 [2 8 10]
   10 [2 3 9 11]
   11 [3 10 12]
   12 [3 4 11 13]
   13 [4 12 14]
   14 [4 5 13 15]
   15 [5 14 16]
   16 [5 6 15 17]
   17 [6 16 18]
   18 [6 7 17 19]
   19 [7 8 18]})

提问者尝试过用map但不确定内部函数,也试过集合求交集但思路有误,需要可行的解决方案。

解决方案

核心思路

判断向量中是否存在相邻瓦片,本质是检查向量中是否有某个瓦片的相邻列表包含向量里的另一个瓦片。为了高效判断,可先把向量转为集合(集合查找为O(1)),再遍历每个瓦片,检查它的相邻列表与该集合是否有交集——只要有一个瓦片满足条件,就返回true,否则返回false。

实现代码(交集版)

(defn has-adjacent-tiles? [tiles]
  (let [tile-set (set tiles)]
    (some (fn [tile]
            (not-empty (clojure.set/intersection tile-set (set (adjacents tile)))))
          tiles)))

代码解释

  1. (set tiles):将输入向量转为集合,提升后续查找效率
  2. some函数:遍历每个瓦片,只要找到第一个让传入函数返回非nil值的元素,就立即返回该值(非空交集会返回集合,视为true)
  3. clojure.set/intersection:计算当前瓦片的相邻列表(转为集合)与输入瓦片集合的交集,非空则说明当前瓦片和向量中另一瓦片相邻

简化实现(直接检查版)

若不想用集合交集,也可直接遍历每个瓦片的相邻列表,检查是否有元素存在于输入瓦片集合中:

(defn has-adjacent-tiles? [tiles]
  (let [tile-set (set tiles)]
    (some (fn [tile]
            (some #(contains? tile-set %) (adjacents tile)))
          tiles)))

这个版本逻辑更直观:对每个瓦片,检查其相邻列表里是否有元素在输入集合中,找到一个就返回true。

测试验证

(has-adjacent-tiles? [1 3 19]) ; => true
(has-adjacent-tiles? [1 14 19]) ; => false

内容的提问来源于stack exchange,提问作者triplej

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 22:57:20