zoukankan      html  css  js  c++  java
  • [Leetcode 98] 54 Spiral Matrix

    Problem:

    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

    For example,
    Given the following matrix:

    [
     [ 1, 2, 3 ],
     [ 4, 5, 6 ],
     [ 7, 8, 9 ]
    ]
    

    You should return [1,2,3,6,9,8,7,4,5].

    Analysis:

    The problem is a simulation problem. With the help of a direction variable, we can go through the matrix. When a new position is not valid, then we must change the direction.

    For a index (i, j) to be valid, the following creteria must be satisfied:

    1. i >=0 && i < row

    2. j>=0 && j < col

    3. m[i][j] is not visited

    Direction changes from right -> down -> left -> up.

    Code:

     1 class Solution {
     2 public:
     3     int row, col, MIN = (1<<31);
     4 
     5     vector<int> spiralOrder(vector<vector<int> > &matrix) {
     6         // Start typing your C/C++ solution below
     7         // DO NOT write int main() function
     8         vector<int> res;
     9         
    10         if (matrix.size() == 0)
    11             return res;
    12             
    13         row = matrix.size(), col = matrix[0].size();
    14         int dir = 0, size = row * col;
    15         int row_dir[4] = {0, 1, 0, -1};
    16         int col_dir[4] = {1, 0, -1, 0};
    17         
    18         int i=0, j=-1, total = 0;
    19         while (true) {
    20             i += row_dir[dir];
    21             j += col_dir[dir];
    22             
    23             if (isValid(i, j, matrix)) {
    24                 res.push_back(matrix[i][j]);
    25                 matrix[i][j] = MIN;
    26                 total += 1;
    27                 if (total == size) break;
    28             } else {
    29                 // reset to last valid position
    30                 i -= row_dir[dir];
    31                 j -= col_dir[dir];
    32                 dir = (dir + 1) % 4;
    33             }
    34         }
    35         
    36         return res;
    37     }
    38     
    39     bool isValid(int i, int j, vector<vector<int> > & m) {
    40         return (i < row && i>=0) &&( j>=0 && j < col) && (m[i][j] != MIN);
    41     }
    42 };
    View Code
  • 相关阅读:
    斐波那契数列 的两种实现方式(Java)
    单链表反转
    单链表合并
    两个有序list合并
    list去重 转载
    RemoveAll 要重写equals方法
    Java for LeetCode 138 Copy List with Random Pointer
    Java for LeetCode 137 Single Number II
    Java for LeetCode 136 Single Number
    Java for LeetCode 135 Candy
  • 原文地址:https://www.cnblogs.com/freeneng/p/3240599.html
Copyright © 2011-2022 走看看