日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

数据结构与算法之“之”字型打印矩阵和矩阵中找数

發布時間:2024/2/28 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 数据结构与算法之“之”字型打印矩阵和矩阵中找数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

數據結構與算法之“之”字型打印矩陣和矩陣中找數


目錄

  • “之”字型打印矩陣
  • 在行列都排好序的矩陣中找數

  • 1. “之”字型打印矩陣

  • 題目描述

  • 思路:創建A,B兩個點,A往右移,B往下移,當移到最右邊和最下邊則向下移和右移。AB兩點連線即為打印路徑,添加個flag判斷從下打印還是從上打印即可。

  • 代碼實現
  • public class Code_ZigZagPrintMatrix {public static void printMatrixZigZag(int[][] matrix) {int aR = 0;int aC = 0;int bR = 0;int bC = 0;int endR = matrix.length - 1;int endC = matrix[0].length - 1;boolean fromUp = false;while (aR != endR + 1) {printLevel(matrix, aR, aC, bR, bC, fromUp);aR = aC == endC ? aR + 1 : aR;aC = aC == endC ? aC : aC + 1;bC = bR == endR ? bC + 1 : bC;bR = bR == endR ? bR : bR + 1;fromUp = !fromUp;}System.out.println();}public static void printLevel(int[][] m, int aR, int aC, int bR, int bC,boolean f) {if (f) {while (aR != bR + 1) {System.out.print(m[aR++][aC--] + " ");}} else {while (bR != aR - 1) {System.out.print(m[bR--][bC++] + " ");}}}public static void main(String[] args) {int[][] matrix = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };printMatrixZigZag(matrix);} }
  • 編譯結果

  • 在行列都排好序的矩陣中找數

  • 題目描述

  • 思路:從右上角出去,當找的數比當前數大時,則向下走,如果找的數比當前數小數則向左走,沒找到就返回false。

  • 代碼實現
  • public class Code_FindNumInSortedMatrix {public static boolean isContains(int[][] matrix, int K) {int row = 0;int col = matrix[0].length - 1;while (row < matrix.length && col > -1) {if (matrix[row][col] == K) {return true;} else if (matrix[row][col] > K) {col--;} else {row++;}}return false;}public static void main(String[] args) {int[][] matrix = new int[][] { { 0, 1, 2, 3, 4, 5, 6 },// 0{ 10, 12, 13, 15, 16, 17, 18 },// 1{ 23, 24, 25, 26, 27, 28, 29 },// 2{ 44, 45, 46, 47, 48, 49, 50 },// 3{ 65, 66, 67, 68, 69, 70, 71 },// 4{ 96, 97, 98, 99, 100, 111, 122 },// 5{ 166, 176, 186, 187, 190, 195, 200 },// 6{ 233, 243, 321, 341, 356, 370, 380 } // 7};int K = 233;System.out.println(isContains(matrix, K));}}

    總結

    以上是生活随笔為你收集整理的数据结构与算法之“之”字型打印矩阵和矩阵中找数的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。