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

Swift二维数组:获取值为0且索引最小的元素求助

解决二维数组中查找第一个值为0的元素问题

Hey Jonas, sorry your code isn't working out—let's get this sorted for you!

First off, let's make sure we're on the same page: you want to find the first occurrence of 0 in your 2D array (the one with the smallest indices, checking row by row left to right, then top to bottom). That makes sense!

Quick Example to Set the Scene

Say your 2D array looks like this:

my_2d_array = [
    [1, 4, 7],
    [2, 0, 8],
    [3, 5, 0]
]

The first 0 here is at index (1, 1) (if we're using 0-based counting) — that's the one we want to grab.

Why Your Code Might Be Failing

Even though you didn't share your code, the most common issues here are:

  • Not stopping the search as soon as you find the first 0 (so you end up grabbing a later one instead)
  • Traversing the array in the wrong order (like column-first instead of row-first) which would skip the smallest-indexed 0

Working Solutions (Python Example)

Here are two straightforward ways to get what you need, depending on whether you want the element's indices or the element itself:

1. Get the Indices of the First 0

def find_first_zero_indices(arr):
    for row_num, row in enumerate(arr):
        for col_num, value in enumerate(row):
            if value == 0:
                return (row_num, col_num)
    # If no 0 exists in the array, return a default value (adjust as needed)
    return None

# Test it out
my_2d_array = [[1,4,7],[2,0,8],[3,5,0]]
print(find_first_zero_indices(my_2d_array))  # Output: (1, 1)

2. Get the First 0 Element Directly

def get_first_zero_element(arr):
    for row in arr:
        for value in row:
            if value == 0:
                return value
    # No 0 found? Return a default
    return None

print(get_first_zero_element(my_2d_array))  # Output: 0

How This Works

  • We loop through the array row by row, left to right — this ensures we check elements in order of their index size
  • As soon as we hit a 0, we immediately return it (or its indices) — this stops the search right away, so we don't waste time checking later elements
  • If there's no 0 in the array, we return None — you can swap this out for something else (like -1) if that fits your use case better

If you're working with a different language (like JavaScript, Java, etc.), just let me know and I can tweak this solution to match!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:00:59