当前位置:网站首页>2021-04-02: given a square or rectangular matrix, zigzag printing can be realized.

2021-04-02: given a square or rectangular matrix, zigzag printing can be realized.

2022-06-24 16:56:00 Fuda scaffold constructor's daily question

2021-04-02: Given a square or rectangular matrix matrix, Realization zigzag Print .[0,1,2,3,4,5,6,7,8] What is the order of printing 0,1,3,6,4,2,5,7,8.

Fuda answer 2021-04-02:

Two for A nested loop .

The outer loop . First traverse the first column , The traversal does not include the column number as 0 Last line . Every cycle , Modify flag bit .

Inner circulation . According to the flag bit , From bottom left to top right , Or from top right to bottom left .

The code to use golang To write . The code is as follows :

package main

import "fmt"

func main() {
    arr := [][]int{
        {0, 1, 2},
        {3, 4, 5},
        {6, 7, 8}}
    printMatrixZigZag(arr)
}
func printMatrixZigZag(matrix [][]int) {
    row := len(matrix)
    col := len(matrix[0])
    fromUp := false
    // Traverse the first column 
    for i := 0; i < row; i++ {
        if fromUp {
            // Find the top right position 
            j := 0
            for ; i-j >= 0 && j < col; j++ {
            }
            j--

            // Top right to bottom left 
            for ; j >= 0; j-- {
                fmt.Print(matrix[i-j][0+j], " ")
            }
        } else {
            // From bottom left to top right 
            for j := 0; i-j >= 0 && j < col; j++ {
                fmt.Print(matrix[i-j][0+j], " ")
            }
        }
        fromUp = !fromUp
    }

    // Traverse the last line 
    for j := 1; j < col; j++ {
        if fromUp {
            // Find the top right position 
            i := 0
            for ; row-1-i >= 0 && j+i < col; i++ {
            }
            i--

            // Top right to bottom left 
            for ; i >= 0; i-- {
                fmt.Print(matrix[row-1-i][j+i], " ")
            }
        } else {
            // From bottom left to top right 
            for i := 0; row-1-i >= 0 && j+i < col; i++ {
                fmt.Print(matrix[row-1-i][j+i], " ")
            }
        }
        fromUp = !fromUp
    }
}

The results are as follows :

Insert picture description here

Zuo Shen java Code

Comment on

原网站

版权声明
本文为[Fuda scaffold constructor's daily question]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/04/20210403111047585w.html