@@ -216,8 +216,131 @@ public class Main {
216
216
217
217
### Python
218
218
219
+ ``` python
220
+
221
+ def main ():
222
+ import sys
223
+ input = sys.stdin.read
224
+ data = input ().split()
225
+
226
+ # 读取 n 和 m
227
+ n = int (data[0 ])
228
+ m = int (data[1 ])
229
+
230
+ # 初始化 grid
231
+ grid = []
232
+ index = 2
233
+ for i in range (n):
234
+ grid.append([int (data[index + j]) for j in range (m)])
235
+ index += m
236
+
237
+ sum_land = 0 # 陆地数量
238
+ cover = 0 # 相邻数量
239
+
240
+ for i in range (n):
241
+ for j in range (m):
242
+ if grid[i][j] == 1 :
243
+ sum_land += 1
244
+ # 统计上边相邻陆地
245
+ if i - 1 >= 0 and grid[i - 1 ][j] == 1 :
246
+ cover += 1
247
+ # 统计左边相邻陆地
248
+ if j - 1 >= 0 and grid[i][j - 1 ] == 1 :
249
+ cover += 1
250
+ # 不统计下边和右边,避免重复计算
251
+
252
+ result = sum_land * 4 - cover * 2
253
+ print (result)
254
+
255
+ if __name__ == " __main__" :
256
+ main()
257
+
258
+
259
+ ```
260
+
219
261
### Go
220
262
263
+ ``` go
264
+
265
+ package main
266
+
267
+ import (
268
+ " bufio"
269
+ " fmt"
270
+ " os"
271
+ " strconv"
272
+ " strings"
273
+ )
274
+
275
+ func main () {
276
+ scanner := bufio.NewScanner (os.Stdin )
277
+ scanner.Scan ()
278
+ line := scanner.Text ()
279
+
280
+ n , m := parseInput (line)
281
+
282
+ // 初始化 grid
283
+ grid := make ([][]int , n)
284
+ for i := range grid {
285
+ grid[i] = make ([]int , m)
286
+ }
287
+
288
+ // 读入 grid 数据
289
+ for i := 0 ; i < n; i++ {
290
+ scanner.Scan ()
291
+ line := scanner.Text ()
292
+ values := parseLine (line, m)
293
+ for j := 0 ; j < m; j++ {
294
+ grid[i][j] = values[j]
295
+ }
296
+ }
297
+
298
+ sum := 0 // 陆地数量
299
+ cover := 0 // 相邻数量
300
+
301
+ for i := 0 ; i < n; i++ {
302
+ for j := 0 ; j < m; j++ {
303
+ if grid[i][j] == 1 {
304
+ sum++ // 统计总的陆地数量
305
+
306
+ // 统计上边相邻陆地
307
+ if i-1 >= 0 && grid[i-1 ][j] == 1 {
308
+ cover++
309
+ }
310
+ // 统计左边相邻陆地
311
+ if j-1 >= 0 && grid[i][j-1 ] == 1 {
312
+ cover++
313
+ }
314
+ // 为什么没统计下边和右边? 因为避免重复计算
315
+ }
316
+ }
317
+ }
318
+
319
+ fmt.Println (sum*4 - cover*2 )
320
+ }
321
+
322
+ // parseInput 解析 n 和 m
323
+ func parseInput (line string ) (int , int ) {
324
+ parts := strings.Split (line, " " )
325
+ n , _ := strconv.Atoi (parts[0 ])
326
+ m , _ := strconv.Atoi (parts[1 ])
327
+ return n, m
328
+ }
329
+
330
+ // parseLine 解析一行中的多个值
331
+ func parseLine (line string , count int ) []int {
332
+ parts := strings.Split (line, " " )
333
+ values := make ([]int , count)
334
+ for i := 0 ; i < count; i++ {
335
+ values[i], _ = strconv.Atoi (parts[i])
336
+ }
337
+ return values
338
+ }
339
+
340
+
341
+ ```
342
+
343
+
221
344
### Rust
222
345
223
346
### Javascript
0 commit comments